PHP
Aggregating Array Values with array_reduce()
Master `array_reduce()` in PHP to iteratively combine all array elements into a single value, perfect for calculating sums, concatenations, or complex aggregations.
<?php
$numbers = [1, 2, 3, 4, 5];
// Calculate the sum of all numbers
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0); // 0 is the initial value for $carry
echo "Sum: " . $sum . "
";
echo "
";
$words = ['Hello', 'World', 'PHP'];
// Concatenate words into a single string
$sentence = array_reduce($words, function($carry, $item) {
return $carry === '' ? $item : $carry . ' ' . $item;
}, '');
echo "Sentence: " . $sentence . "
";
?>
How it works: The `array_reduce()` function reduces an array to a single value by iteratively applying a callback function to each element. It takes an initial value (`carry`) and the current array item, returning an updated `carry` for the next iteration. This makes it versatile for summing, concatenating, or performing more complex aggregations on array data, providing a powerful way to process collections.