Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP – array_diff does not work as it supposed to

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

array_diff only checks for values, no checks for keys

you need to use array_diff_assoc to check along with keys

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading