phparraysfilterarray-difference

array_diff() is filtering out elements with the same value even if their associative keys do not match


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" => "No",
    "INDEX4" => "No"
)

Can anybody help me to understand what is happening?


Solution

  • 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.