PHP

Calculate Aggregates for an Array Column

Learn to calculate common aggregates like sum and average for a specific numeric column within an array of associative arrays or objects in PHP using `array_column` and `array_sum`.

<?php

$transactions = [
    ['id' => 101, 'amount' => 150.75, 'type' => 'sale'],
    ['id' => 102, 'amount' => 25.50, 'type' => 'refund'],
    ['id' => 103, 'amount' => 300.00, 'type' => 'sale'],
    ['id' => 104, 'amount' => 75.25, 'type' => 'sale'],
    ['id' => 105, 'amount' => 50.00, 'type' => 'refund'],
];

// Get all amounts
$amounts = array_column($transactions, 'amount');

// Calculate sum of amounts
$totalAmount = array_sum($amounts);
echo "Total Amount: " . $totalAmount . "
"; // Output: Total Amount: 601.5

// Calculate average of amounts
$averageAmount = count($amounts) > 0 ? $totalAmount / count($amounts) : 0;
echo "Average Amount: " . $averageAmount . "
"; // Output: Average Amount: 120.3

// Calculate sum of only 'sale' transactions
$saleAmounts = array_column(
    array_filter($transactions, fn($t) => $t['type'] === 'sale'),
    'amount'
);
$totalSaleAmount = array_sum($saleAmounts);
echo "Total Sale Amount: " . $totalSaleAmount . "
"; // Output: Total Sale Amount: 526

// Find max amount
$maxAmount = count($amounts) > 0 ? max($amounts) : 0;
echo "Max Amount: " . $maxAmount . "
"; // Output: Max Amount: 300
How it works: This snippet demonstrates how to perform aggregate calculations (sum, average, max) on a specific numeric "column" from an array of associative arrays. It uses `array_column` to extract the relevant numbers, then `array_sum`, `count`, and `max` functions to compute the aggregates. It also shows conditional aggregation by filtering first.

Need help integrating this into your project?

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

Hire DigitalCodeLabs