-2

I have 2 array, I want to compare them by matched values and order and count of total eligible values.

$a = [A,B,C,D,E,F,G];
          | |     |
$b = [B,A,C,D,F,E,G];

In this case the output should be 3 . How can I achieve this with top performance?

Update:

I am not asking matched values only , values should matched at the same order as well.

OMahoooo
  • 427
  • 3
  • 9
  • 19

2 Answers2

1

Array_diff_assoc will count what is not the same (4).
Count will count the number of items (7).
7-4 = 3.

echo count($a) - count(array_diff_assoc($a,$b)); // 3

https://3v4l.org/OIknS

Edit or just array_intersect_assoc

echo count(array_intersect_assoc($a,$b)); //3

Didn't cross my mind until now.

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

Assuming that both arrays have the same size you can do it with a simple loop:

$count = 0;

foreach ($a as $key => $value) {
    if ($value === $b[$key]) {
        $count++;
    }
}

var_dump($count);

If they have different sizes then you must check if the key exists in the second array too.

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50