PHP
Aggregating Array Data with PHP's array_reduce
Master `array_reduce` to consolidate a PHP array into a single value. Perform powerful aggregations like sum, average, or string concatenation efficiently for dynamic data processing.
<?php
$numbers = [10, 20, 30, 40, 50];
// Calculate the sum of all numbers
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0); // 0 is the initial carry value
echo "Sum: " . $sum . "
"; // Output: Sum: 150
$words = ['Hello', 'World', 'PHP', 'Arrays'];
// Concatenate words into a single string
$sentence = array_reduce($words, function($carry, $item) {
return $carry . ($carry ? ' ' : '') . $item;
}, ''); // Empty string is the initial carry value
echo "Sentence: " . $sentence . "
"; // Output: Sentence: Hello World PHP Arrays
// Calculate average
$data = [10, 20, 30, 40];
$average = array_reduce($data, function($carry, $item) {
static $count = 0; // Static counter
$count++;
$carry['sum'] += $item;
$carry['count'] = $count;
return $carry;
}, ['sum' => 0, 'count' => 0]);
if ($average['count'] > 0) {
echo "Average: " . ($average['sum'] / $average['count']) . "
"; // Output: Average: 25
}
?>
How it works: The `array_reduce()` function iteratively reduces the array to a single value using a callback function. The callback receives a `carry` (the accumulated value) and the current `item` from the array. An optional `initial` value can be provided for the `carry`. This function is incredibly versatile for tasks like summing values, concatenating strings, or performing complex data transformations into a single result.