Search code examples
phparraysarray-difference

PHP compare arrays


I have two arrays. $arrayOld and $arrayNew and I want to compare these arrays and only select the values that are not in $arrayNew.

I don't want the values that are in $arrayNew only. So I don't think array_diff() is gonna help me.

$arrayOld = [1, 2, 3, 4, 5]
$arrayNew = [1, 4, 5, 6, 7]

So it only needs to return 2 and 3 and not 6 or 7.


Solution

  • use array_diff, to accomplish this. As you need to difference between the array and need data from Old array so you need to use the old array as the first parameter of the array_diff.

    Note: Array diff only returns from the first array which is not in second array.

    $arrayOld = [1, 2, 3, 4, 5];
    $arrayNew = [1, 4, 5, 6, 7];
    
    $n = array_diff($arrayOld, $arrayNew);
    
    print_r($n);
    

    Result: Online Check

    Array
    (
        [1] => 2
        [2] => 3
    )
    

    If you need a new keys for the output array just use array_values. The new key start from 0.

    $arr = array_values($n);