'While comparing associative rows between two 2d arrays, array_diff_assoc() gives the wrong difference

i have two arrays, and i use array_diff_assoc() php function for get the difference, but it always returns the comm set as the difference, but it should be new q sets whats the wrong with this, please help

arrays--

Array ( [0] => Array ( [12] => new q sets ) [1] => Array ( [11] => common set ) ) 

Array ( [0] => Array ( [11] => common set ) ) 

after use array_diff_assoc() o p

Array ( [1] => Array ( [11] => common set ) ) 


Solution 1:[1]

in array_diff_assoc(), keys are also compared. Since [0] is available in second array and [1] is not available in second array so thats why the result is Array ( [1] => Array ( [11] => common set ) ) .

Solution 2:[2]

When running your script in a modern php environment, the Warnings should indicate that you are using the wrong tool for the job.

Bad Code: (Demo)

$array1 = [[12 => 'new q sets'], [11 => 'common set']];
$array2 = [[11 => 'common set']];

var_export(array_diff_assoc($array1, $array2));

Bad Output:

Warning: Array to string conversion in /in/jIUcq on line 6

Warning: Array to string conversion in /in/jIUcq on line 6
array (
  1 => 
  array (
    11 => 'common set',
  ),
)

You don't actually want to compare the first level indexes anyhow because related/matching rows may have different first level indexes.


Instead, you should use array_udiff() to compare the associative rows (and ignore the first level keys). Making a 3-way comparison -- as array_udiff() expects from the callback -- without iterated function calls is possible with the "spaceship operator". In the below snippet, $a and $b represent rows of data.

Proper Code: (Demo)

var_export(
    array_udiff($array1, $array2, fn($a, $b) => $a <=> $b)
);

Proper Output:

array (
  0 => 
  array (
    12 => 'new q sets',
  ),
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Neeraj
Solution 2 mickmackusa