PHP

How to Calculate Sum and Average of Array Values Using `array_reduce` in PHP

Aggregate array elements into a single result by applying a callback function iteratively. Calculate sum, average, or perform other complex reductions.

<?php
$grades = [85, 92, 78, 95, 88];

// Calculate sum
$sum = array_reduce($grades, function($carry, $item) {
    return $carry + $item;
}, 0); // 0 is the initial value for $carry
echo "Sum of grades: {$sum}
"; // Output: Sum of grades: 438

// Calculate average
$count = count($grades);
$average = ($count > 0) ? ($sum / $count) : 0;
echo "Average grade: {$average}
"; // Output: Average grade: 87.6

// A more complex reduction: find the highest grade
$highestGrade = array_reduce($grades, function($carry, $item) {
    return max($carry, $item);
}, $grades[0] ?? 0); // Initial carry can be the first element or a default
echo "Highest grade: {$highestGrade}
"; // Output: Highest grade: 95
?>
How it works: The `array_reduce()` function iterates over an array, passing the value from the previous iteration (or an initial value) and the current array element to a callback function. This powerful function aggregates an array into a single value, making it ideal for tasks like calculating sums, averages, finding minimum/maximum values, or building complex data structures.

Need help integrating this into your project?

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

Hire DigitalCodeLabs