PHP

Calculate Sum and Average of Array Column

Learn to calculate the sum and average of a specific numeric column within an array of associative arrays in PHP, useful for data aggregation.

<?php
$salesData = [
    ['product' => 'A', 'quantity' => 10, 'price' => 15.50],
    ['product' => 'B', 'quantity' => 5, 'price' => 20.00],
    ['product' => 'C', 'quantity' => 12, 'price' => 10.25],
    ['product' => 'D', 'quantity' => 8, 'price' => 50.00],
];

// Extract the 'quantity' column
$quantities = array_column($salesData, 'quantity');
$totalQuantity = array_sum($quantities);
$averageQuantity = count($quantities) > 0 ? $totalQuantity / count($quantities) : 0;

echo "Total Quantity: " . $totalQuantity . "
";
echo "Average Quantity: " . round($averageQuantity, 2) . "
";

// Calculate total sales value
$totalSalesValue = array_reduce($salesData, function($sum, $item) {
    return $sum + ($item['quantity'] * $item['price']);
}, 0);

echo "Total Sales Value: " . round($totalSalesValue, 2) . "
";
?>
How it works: This snippet demonstrates how to perform aggregations on a specific numeric column within an array of associative arrays. It uses `array_column()` to extract all values for a given key (e.g., 'quantity') into a new array. Then, `array_sum()` calculates the total, and simple division yields the average. It also shows `array_reduce()` for more complex aggregations, like calculating total sales value.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs