Thursday, 30 August 2018

Why does array_diff () compare two different arrays and return the empty result?

I have this code:

$a1 = array(31001);
$a2 = array(31001, 31002);
$diff = array_diff($a1, $a2);
var_dump($diff);

I was expecting that array_diff will return array(0 => 31002) according to PHP documentation:
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
However posted code returns empty array. Anyone can explain me why is this happening and how to get correct result ?
Thanks for any help or helpful hints.

Read the documentation exactly. The set of values that are present in $a1 and not present in $a2 is empty: $a1 just contains one element (31001), which is also present in $a2.
You want to get all values that are present in $a2, but not in $a1, so you have to switch the order of the arrays, you pass to array_diff():
$diff = array_diff($a2, $a1);

0 comments:

Post a Comment