Search code examples
phparraysarray-difference

Save difference of two arrays in another array in PHP


I'm trying to save the difference of two arrays in a new one.

I've used array_diff and the code I have right now is partially working but it seems that the new array saves the elements in wrong position.

<?php 
    // Arrays to hold the numbers for this demo
    $arr1 = array(5,6,7,8);
    $arr2 = array(2,5,6);
    $arr3 = array_diff($arr1, $arr2);

    // Correct result but in wrong positions in the array
    var_dump($arr3); // array(2) { [2]=> int(7) [3]=> int(8) }
?>

How is it possible to have a value at position 2 and 3 of an array of size 2?

Any explanation on the cause of this issue is greatly appreciated, thank you.


Solution

  • Because arrays don't have to start at zero. As you can see, array_diff() will preserve keys.

    If you want to reset the array keys you can use array_values():

    // Arrays to hold the numbers for this demo
    $arr1 = array(5,6,7,8);
    $arr2 = array(2,5,6);
    $arr3 = array_values(array_diff($arr1, $arr2));
    var_dump($arr3);
    

    Output:

    array(2) {
      [0]=>
      int(7)
      [1]=>
      int(8)
    }
    

    Demo