Difference between two array values

I have two arrays which contain product code as key and quantity as value ('code' => quantity). I would like to create an array that contains the difference between the old array (array1) and the new array (array2), including any added or removed code from array1 to array2.

$array1 = ['code1' => 1, 'code2' => 2];    
$array2 = ['code1' => 0, 'code2' => 2, 'code3' => 3];

// Array expected
$diffQty = [
    'code1' => -1, // 1 quantity deleted in array 2
    'code2' => 0, // quantity no changed between array1 and array2
    'code3' => 3  // new code added in array2 with 3 quantity
];

      

I tried something like this, but I didn't add or remove code between the arrays:

$diffQty = [];
foreach ($array2 as $code => $qty) {
    if (array_key_exists($code, $array1)) {
        $diffQty = $array1[$code] - $array2[$code];
        $diffQty[$code] = $diffQty;
    }
}

      

+3


source to share


1 answer


Your current problem is that you are not doing anything in the case where the key does not exist in both arrays.

Get all the unique keys that exist and put them in a separate array. Complete the resulting array, which now contains all the keys that exist in both arrays $array1

and $array2

. Subtract the values ​​in $array1

from $array2

, and if there is no key in any of the arrays, it defaults to zero.

$array1 = ['code1' => 1, 'code2' => 2];    
$array2 = ['code1' => 0, 'code2' => 2, 'code3' => 3];
$all_keys = array_unique(array_merge(array_keys($array1), array_keys($array2)));
$output = array();

foreach ($all_keys as $code) {
    $output[$code] = (!empty($array2[$code]) ? $array2[$code] : 0) - (!empty($array1[$code]) ? $array1[$code] : 0);
}

      



Result $output

Array (
    [code1] => -1
    [code2] => 0
    [code3] => 3
)

      

Live demo

+2


source







All Articles