Damosse31
Damosse31

Reputation: 452

Difference quantity between two arrays values

I have two arrays who contains product code as key and quantity as value ('code' => quantity). I would like to generate an array who contain difference of quantity between old array (array1) and new array (array2), including any code added or deleted 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 don't have added or deleted code between arrays :

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

Upvotes: 3

Views: 93

Answers (1)

Qirel
Qirel

Reputation: 26460

Your current issue is that you don't do anything in the case where the key doesn't exist in both arrays.

Fetch all the unique keys that exists, and put that into a separate array. Loop the resulting array, which now contains all the keys that exists in both arrays $array1 and $array2. Subtract the values in $array1 from $array2, and if there is no key valid in either array, default it 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 of $output

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

Live demo

Upvotes: 2

Related Questions