PHP
Aggregate Array Elements into a Single Value with `array_reduce`
Master `array_reduce` to iterate through a PHP array and combine its elements into a single result, useful for sums, concatenations, or complex aggregations.
<?php
$numbers = [10, 20, 30, 40];
// Example 1: Sum all numbers
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);
echo "Numbers: " . implode(', ', $numbers) . "
";
echo "Sum of numbers: " . $sum . "
";
$words = ['hello', 'world', 'php', 'developers'];
// Example 2: Concatenate words into a sentence
$sentence = array_reduce($words, function($carry, $item) {
return $carry . ' ' . $item;
}, 'Welcome'); // 'Welcome' is the initial value
echo "Words: " . implode(', ', $words) . "
";
echo "Concatenated sentence: " . $sentence . "
";
$cartItems = [
['name' => 'Shirt', 'price' => 25, 'qty' => 2],
['name' => 'Pants', 'price' => 50, 'qty' => 1],
['name' => 'Shoes', 'price' => 75, 'qty' => 1]
];
// Example 3: Calculate total cart value
$totalCartValue = array_reduce($cartItems, function($carry, $item) {
return $carry + ($item['price'] * $item['qty']);
}, 0);
echo "Cart Items:
";
print_r($cartItems);
echo "Total Cart Value: $" . $totalCartValue . "
";
?>
How it works: The `array_reduce()` function iterates over an array, applying a callback function to each element and progressively building up a single return value. It takes an array, a callback function, and an optional initial value for the 'carry' accumulator. This powerful function is perfect for tasks like summing, concatenating, or performing complex data aggregations into a single result.