Just found a strange behavior of PHP with the array_diff
function.
I have the following arrays:
$d1 = [
'HomePhoneNumber' => '555-222-2222',
'MobilePhoneNumber' => NULL,
'ContactID' => NULL,
'ApplicantID' => '2'
];
$d2 = [
'HomePhoneNumber' => '555-222-2222',
'MobilePhoneNumber' => '555-222-3333',
'ContactID' => '1',
'ApplicantID' => '2'
];
I need to find the values from $d2
which are not present into $d1
:
array_diff($d2, $d1)
The function returns me:
array (
'MobilePhoneNumber' => '555-222-3333',
'ContactID' => '1',
)
This is correct!
But, if I compare the same arrays with a different value of 'ContactID'
key, the array_diff()
function returns me a different result ('ContactID'
is no longer returned):
$d1 = [
'HomePhoneNumber' => '555-222-2222',
'MobilePhoneNumber' => NULL,
'ContactID' => NULL,
'ApplicantID' => '2'
];
$d2 = [
'HomePhoneNumber' => '555-222-2222',
'MobilePhoneNumber' => '555-222-3333',
'ContactID' => '2',
'ApplicantID' => '2'
];
// Result:
array (
'MobilePhoneNumber' => '555-222-3333',
)
Do you know why? I don't understand. Thanks for you help!
CodePudding user response:
array_diff
only checks for values, no checks for keys
you need to use array_diff_assoc to check along with keys