PHP
Aggregate Array Values with `array_reduce`
Learn to condense an array to a single value in PHP using `array_reduce()`. Perfect for calculating sums, averages, or concatenating strings.
<?php
$numbers = [1, 2, 3, 4, 5];
// Calculate the sum of all numbers
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0); // Initial carry value is 0
echo "Sum: " . $sum . "
"; // Output: Sum: 15
$words = ['Hello', 'World', 'PHP'];
// Concatenate words with a space
$sentence = array_reduce($words, function($carry, $item) {
return $carry === '' ? $item : $carry . ' ' . $item;
}, ''); // Initial carry value is an empty string
echo "Sentence: " . $sentence . "
"; // Output: Sentence: Hello World PHP
?>
How it works: `array_reduce()` iterates over an array, cumulatively building a single result value. It takes the array, a callback function, and an optional initial value for the 'carry' variable. The callback function receives the current 'carry' value and the current array 'item', returning the new 'carry' value. This is powerful for summing, concatenating, or performing other aggregations.