PHP
Aggregate Array Values to a Single Result with a Callback Function
Master array_reduce in PHP to iteratively combine all elements of an array into a single value, perfect for summing, concatenating, or complex aggregations.
<?php
$numbers = [10, 20, 30, 40, 50];
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);
$concatenatedString = array_reduce(['Hello', 'World', '!'], function($carry, $item) {
return $carry . ' ' . $item;
}, '');
print_r("Sum: " . $sum . "
");
// Output: Sum: 150
print_r("Concatenated: " . $concatenatedString);
// Output: Concatenated: Hello World !
How it works: `array_reduce()` is used to iteratively reduce an array to a single value using a callback function. The callback receives a 'carry' value (the accumulated result from the previous iteration) and the current 'item' from the array. This snippet shows how to sum numbers and concatenate strings, but it can be used for any complex aggregation.