PHP
Calculate Sum of Specific Property in Array of Objects
Efficiently sum values from a specific property (key) across an array of associative arrays in PHP, ideal for aggregating totals in reports.
<?php
$cartItems = [
['product' => 'Laptop', 'price' => 1200, 'quantity' => 1],
['product' => 'Mouse', 'price' => 25, 'quantity' => 2],
['product' => 'Keyboard', 'price' => 75, 'quantity' => 1],
['product' => 'Monitor', 'price' => 300, 'quantity' => 1]
];
/**
* Calculates the sum of a specific numeric key from an array of associative arrays.
* @param array $array The input array.
* @param string $key The key whose values are to be summed.
* @return float|int The total sum.
*/
function sumArrayColumn(array $array, string $key)
{
return array_reduce($array, function ($carry, $item) use ($key) {
return $carry + ($item[$key] ?? 0);
}, 0);
}
// Calculate total price of all items
$totalPrice = sumArrayColumn($cartItems, 'price');
echo "Total Price: $" . $totalPrice . "
";
// Calculate total quantity of all items
$totalQuantity = sumArrayColumn($cartItems, 'quantity');
echo "Total Quantity: " . $totalQuantity . "
";
// Calculate sum of 'price' * 'quantity' for total cart value
$totalCartValue = array_reduce($cartItems, function ($carry, $item) {
return $carry + (($item['price'] ?? 0) * ($item['quantity'] ?? 0));
}, 0);
echo "Total Cart Value: $" . $totalCartValue . "
";
/*
Output:
Total Price: $1600
Total Quantity: 5
Total Cart Value: $1675
*/
?>
How it works: This snippet demonstrates how to calculate the sum of values from a specific key within an array of associative arrays. It leverages `array_reduce`, a powerful functional programming tool, to iterate through the array and accumulate a single result. For each item, it adds the value of the specified `$key` (defaulting to 0 if the key is missing using the null coalescing operator `??`) to the running total (`$carry`). This is efficient for generating totals for reports, invoices, or aggregating various metrics.