1

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!

Chris Humbert
  • 13
  • 1
  • 2
  • Obviously, `array_diff` __does not consider__ keys. And value '2' exists in `$d1` – u_mulder Jun 28 '22 at 17:22
  • It might be a side effect of type juggling between the null and the string, see [Example #2 array_diff() example with non-matching types](https://www.php.net/manual/en/function.array-diff.php#example-4934) you could see if you can create a custom comparison using [array_udiff](https://www.php.net/manual/en/function.array-udiff.php) – Scuzzy Jun 28 '22 at 17:22

1 Answers1

1

array_diff only checks for values, no checks for keys

you need to use array_diff_assoc to check along with keys

Kongulov
  • 1,156
  • 2
  • 9
  • 19
  • 2
    Please close duplicate questions instead of answering them. By 2015, virtually all basic questions have been asked and answered 5 or more times. This means that when you see a new basic question asked, it is probably a duplicate (it is not low-hanging fruit, it is forbidden fruit). – mickmackusa Jun 29 '22 at 00:51