PHP array_diff not working on empty array?

Doc states

Compares array against one or more other arrays and returns the values
in array that are not present in any of the other arrays.

Very simple code. array_diff seems to not work when an empty array is passed. Is this the expected behavior ? Feels like it should return ["6310cdc0fee0927a6688a23a"]

 $a = [];
 $b = ["6310cdc0fee0927a6688a23a"];

 var_dump(array_diff($a, $b));

 // array(0) {}

>Solution :

As documented:

Returns an array containing all the entries from array that are not
present in any of the other arrays

Since the array you passed in as the first argument is empty, there are (by definition) no entries in that array which are not present in any of the others!

If you reverse the order of the arguments, you’ll get the result which I think you were probably expecting:

$a = [];
$b = ["6310cdc0fee0927a6688a23a"];

var_dump(array_diff($b, $a));

outputs:

array(1) {
  [0]=>
  string(24) "6310cdc0fee0927a6688a23a"
}

Demo: https://3v4l.org/1shKr

Leave a Reply