PHP
Reduce a PHP Array to a Single Value
Aggregate a PHP array into a single result (e.g., sum, concatenation, max) using array_reduce() and a custom callback function, demonstrating powerful data aggregation.
<?php
$numbers = [1, 2, 3, 4, 5];
// Calculate the sum of all numbers
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0); // Initial value for $carry
echo "Sum: " . $sum . "
"; // Output: Sum: 15
$words = ['hello', 'world', 'php', 'array'];
// Concatenate words with a space
$sentence = array_reduce($words, function($carry, $item) {
return $carry . ($carry ? ' ' : '') . $item;
}, ''); // Initial value for $carry
echo "Sentence: " . $sentence . "
"; // Output: Sentence: hello world php array
// Find the maximum value
$max = array_reduce($numbers, function($carry, $item) {
return max($carry, $item);
}, $numbers[0]); // Start with the first element as initial max
echo "Max: " . $max . "
"; // Output: Max: 5
How it works: The `array_reduce()` function iterates over an array, passing each value to a user-defined callback function. The callback's return value from the previous iteration is passed as the `carry` value in the next iteration. This allows you to accumulate a single result from the array, such as summing all values, concatenating strings, or finding minimum/maximum elements. The optional `initial` parameter sets the starting value for `carry` before the first iteration.