PHP
Calculate Sum of a Specific Column in an Array
Learn to efficiently sum values from a specific column across all items in a PHP array of associative arrays, perfect for calculating totals from dataset.
$orders = [
['id' => 1, 'item' => 'Book', 'quantity' => 2, 'price_per_unit' => 15.50],
['id' => 2, 'item' => 'Pen', 'quantity' => 5, 'price_per_unit' => 2.00],
['id' => 3, 'item' => 'Notebook', 'quantity' => 1, 'price_per_unit' => 10.00],
];
// Calculate total quantity
$totalQuantity = array_sum(array_column($orders, 'quantity'));
// $totalQuantity will be 2 + 5 + 1 = 8
// Calculate total order value (sum of quantity * price_per_unit for each)
$totalValue = array_sum(array_map(function($order) {
return $order['quantity'] * $order['price_per_unit'];
}, $orders));
// $totalValue will be (2*15.50) + (5*2.00) + (1*10.00) = 31 + 10 + 10 = 51
echo "Total Quantity: " . $totalQuantity . "
";
echo "Total Value: " . $totalValue . "
";
How it works: This snippet shows how to sum numeric values from a specific column of a multidimensional array. It uses `array_column()` to extract the desired column into a simple array, then `array_sum()` to calculate the total efficiently. It also demonstrates a more complex summation involving a calculation for each item using `array_map()` before applying `array_sum()`, allowing for derived sums.