I am trying to count the matches between expected
and actual
in a PHP array, I have this…
$array = array(
"item" => array(
'expected' => array(
'1' => 25,
'2' => 4,
'3' => 4,
),
'color' => 'red',
'actual' => array(
'1' => 25,
'2' => 4,
'3' => 3,
),
),
);
foreach ($array as $key => $arrayItem) {
$matches = array (
'matches' => count ( array_intersect ( $arrayItem['expected'], $arrayItem['actual'] ) ),
);
}
echo "Matches = " . $matches['matches'];
I am expecting this to return 2
but it is actually returning 3
. If I change the values like in the example below then it does work…
$array = array(
"item" => array(
'expected' => array(
'1' => 25,
'2' => 84,
'3' => 4,
),
'color' => 'red',
'actual' => array(
'1' => 25,
'2' => 84,
'3' => 3,
),
),
);
foreach ($array as $key => $arrayItem) {
$matches = array (
'matches' => count ( array_intersect ( $arrayItem['expected'], $arrayItem['actual'] ) ),
);
}
echo "Matches = " . $matches['matches'];
Anyone any ideas why the top version is not giving me the expected result?
3
Answers
The count is actually correct.
It doesn’t happen in your second example because you use the numbers 84 and 4, but essentially here are the matches:
$arrayItem['expected'][1]
matches with$arrayItem['actual'][1]
(25 and 25)$arrayItem['expected'][2]
matches with$arrayItem['actual'][2]
(4 and 4)$arrayItem['expected'][3]
matches with$arrayItem['actual'][2]
(4 and 4)The count of 3 is correct.
You can test this by changing your code to the following:
Here you’ll see this output:
Because it returns an array containing all values in array1 whose values exist in all of the parameters.
array_intersect(array $array1, array $array2[, array $... ]): array
https://www.php.net/manual/en/function.array-intersect.php
Maybe you can see it clearly from this perspective:
it returns 2