PHP
Aggregate PHP Array Elements into a Single Value
Learn to use `array_reduce` to iterate through an array and build a single resulting value by repeatedly applying a callback function.
<?php
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, function($carry, $item) {
$carry += $item;
return $carry;
}, 0); // Initial value of carry
echo "Sum: " . $sum . "
";
$items = ['apple', 'banana', 'cherry'];
$sentence = array_reduce($items, function($carry, $item) {
return $carry === '' ? $item : $carry . ', ' . $item;
}, '');
echo "Sentence: " . $sentence . "
";
?>
How it works: The `array_reduce()` function iterates over an array, passing the 'carry' value (the accumulated result) and the current item to a callback function. The callback's return value becomes the new 'carry' value for the next iteration. This is perfect for calculating sums, concatenating strings, or building complex data structures from an array into a single result.