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 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"]

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

 $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

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