PHP
Calculate Sum of a Specific Key in PHP Array of Associative Arrays
Learn to efficiently calculate the total sum of numeric values from a designated key across an array of associative arrays or objects using `array_reduce`.
$products = [
['item' => 'Laptop', 'price' => 1200, 'quantity' => 1],
['item' => 'Mouse', 'price' => 25, 'quantity' => 2],
['item' => 'Keyboard', 'price' => 75, 'quantity' => 1],
['item' => 'Monitor', 'price' => 300, 'quantity' => 2]
];
// Summing a simple key like 'price'
$totalPrice = array_reduce($products, function($carry, $item) {
return $carry + $item['price'];
}, 0);
echo "Total Price: ".$totalPrice."
"; // Expected output: Total Price: 1600
// Summing a calculated value like 'subtotal' (price * quantity)
$totalSubtotal = array_reduce($products, function($carry, $item) {
return $carry + ($item['price'] * $item['quantity']);
}, 0);
echo "Total Subtotal: ".$totalSubtotal."
"; // Expected output: Total Subtotal: 2125
How it works: This snippet demonstrates `array_reduce`, a powerful function for iterating and accumulating a single result from an array. It takes the array, a callback function, and an initial value (the 'carry'). The callback receives the current accumulated value (`$carry`) and the current array item (`$item`). It returns the new accumulated value. This is perfect for calculating sums, averages, or building other aggregated data from complex array structures.