Ernesto Allely Ernesto Allely - 1 month ago 7
PHP Question

Odd behaviour of array_diff

I am running the script below to get the difference between two arrays using array_diff but I am getting an empty array as result.

$a = [
"INDEX1" => "No",
"INDEX2" => "Yes",
"INDEX3" => "No",
"INDEX4" => "No"
];

$b = [
"INDEX1" => "Yes",
"INDEX2" => "Yes",
"INDEX3" => "No",
"INDEX4" => "Yes"
];

print_r( array_diff($a, $b) );

Array
(
)


Shouldn't I get this instead?

Array
(
"INDEX1" => "Yes",
"INDEX4" => "Yes"
)


Can anybody help me to understand what is happening?

Answer

The result is expected: According to the manual:

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

The only values you have are yes and no and both are present in both arrays.

As mentioned in the comments already, you can use array_diff_assoc to check on the keys as well and get the result you need.