PHP Loop – Sum the Value of an Array if the Key Exists

Posted on March 29, 2021 by jamie

Lop the array with foreach, and check if the key exists – if it doesn’t set the value to the quantity, if it does, add it to the existing quantity. The key represents the product. We check if it’s set or not to avoid having the code produce warnings (as you can see this demo produces).

$collectedData = array();
foreach ($rawData as $value) {
    if (!isset($collectedData[$value['sku']]))
        $collectedData[$value['sku']] = $value['quantity'];
        $collectedData[$value['sku']] += $value['quantity'];