phparraysfilterassociative-arrayarray-difference

array_diff() isn't respecting keys when comparing values in two flat associative arrays


array_diff() function not showing correct result:

First Array:-

Array(
    [designation_id] => 1
    [name] => Y
    [fathers_name] => Z
    [mothers_name] => F
    [spouse_name] => d
    [gender] => F
    [last_achieved_degree] => 2
    [date_of_birth] => 1960-10-17
    [date_of_joining] => 1987-02-04
)

Second array:

Array(
    [designation_id] => 9
    [name] => M
    [fathers_name] => N
    [mothers_name] => O
    [spouse_name] => 
    [gender] => M
    [last_achieved_degree] => 1
    [date_of_birth] => 1967-11-17
    [date_of_joining] => 2016-01-01
)

Output:

Array
(
    [name] => Y
    [fathers_name] => Z
    [mothers_name] => F
    [spouse_name] => d
    [gender] => F
    [last_achieved_degree] => 2
    [date_of_birth] => 1960-10-17
    [date_of_joining] => 1987-02-04
)

The designation_id column is not showing in output result. If the designation_id value is 1 then this index not showing in output otherwise it showing. Is it bug or something else?


Solution

  • Since your arrays are associative arrays, so you need to use array_diff_assoc:-

    <?php
    
     $a =   Array(
        'designation_id' =>1,
        'name' => 'Y',
        'fathers_name' => 'Z',
        'mothers_name' => 'F',
        'spouse_name' => 'd',
        'gender' => 'F',
        'last_achieved_degree' => 2,
        'date_of_birth' => '1960-10-17',
        'date_of_joining' => '1987-02-04'
    );
    
    $b =Array
    (
        'designation_id' => 9,
        'name' => 'M',
        'fathers_name' => 'N',
        'mothers_name' => 'O',
        'spouse_name' => '',
        'gender' => 'M',
        'last_achieved_degree' => 1,
        'date_of_birth' => '1967-11-17',
        'date_of_joining' => '2016-01-01',
    );
    
    echo "<pre/>";print_r(array_diff_assoc($a,$b));
    

    Output:- https://3v4l.org/NKbuX

    To check more descriptions and examples:- https://www.php.net/manual/en/function.array-diff-assoc.php

    Why array_diff() not worked:- https://stackoverflow.com/a/4742438/4248328