PHP
Aggregating PHP Array Elements with `array_reduce`
Learn to iterate over an array and reduce it to a single value using `array_reduce`, perfect for summing, concatenating, or complex custom aggregations.
<?php
$numbers = [1, 2, 3, 4, 5];
$words = ['PHP', 'is', 'awesome'];
// Sum all numbers in the array
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0); // 0 is the initial value for $carry
echo "Sum of numbers: " . $sum . "
";
// Expected: 15
// Concatenate words into a sentence
$sentence = array_reduce($words, function($carry, $item) {
return $carry === '' ? $item : $carry . ' ' . $item;
}, ''); // Empty string as initial value
echo "Concatenated sentence: " . $sentence . "
";
// Expected: PHP is awesome
// Calculate product of numbers, starting with an initial value of 1
$product = array_reduce($numbers, function($carry, $item) {
return $carry * $item;
}, 1);
echo "Product of numbers: " . $product . "
";
// Expected: 120 (1*2*3*4*5)
// Count array elements matching a condition
$evenCount = array_reduce($numbers, function($carry, $item) {
return $carry + ($item % 2 === 0 ? 1 : 0);
}, 0);
echo "Number of even elements: " . $evenCount . "
";
// Expected: 2 (2 and 4)
?>
How it works: The `array_reduce()` function iterates over an array, passing the value of each element to a callback function. The return value of the callback is then used as the `carry` (accumulator) argument in the next iteration. This process effectively 'reduces' the entire array to a single value, making it ideal for calculations like sums, products, concatenations, or other complex aggregations.