PHP
Aggregate Array Elements with `array_reduce`
Learn to process a PHP array into a single resultant value (e.g., sum, product, concatenation) using the powerful `array_reduce` function with a custom callback.
<?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 . "
"; // Expected output: Sum: 15
// Concatenate strings with a separator
$words = ['Hello', 'World', 'PHP', 'Arrays'];
$sentence = array_reduce($words, function($carry, $item) {
return $carry === '' ? $item : $carry . ' ' . $item;
}, '');
echo "Sentence: " . $sentence . "
"; // Expected output: Sentence: Hello World PHP Arrays
?>
How it works: The `array_reduce()` function iterates over an array and reduces it to a single value using a callback function. The callback receives two arguments: the `carry` (the accumulated value from the previous iteration) and the current `item`. An optional initial value can be provided for `carry`. This snippet shows how to calculate a sum and concatenate strings, illustrating its versatility for various aggregation tasks.