skip to Main Content

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) {}

3

Answers


  1. 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

    Login or Signup to reply.
  2. According to documentation
    array_diff

    array_diff – Manual

    In your code example, you have an empty array $a and an array $b with one element. Since the empty array has no values, there are no values to compare with the values in $b. Therefore, the result of array_diff($a, $b) will be an empty array, as there are no values in $a that are not present in $b

    Login or Signup to reply.
  3. It seems that you want to obtain the difference set between two arrays, then you can do:

    $intersect = array_intersect($a, $b);
    $diff_a = array_diff($a, $intersect);
    $diff_b = array_diff($b, $intersect);
    $diff = array_merge($diff_a, $diff_b);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search