PHP
Aggregate Array Values Using array_reduce
Understand how to reduce a PHP array to a single value by iteratively applying a callback function to each element with `array_reduce`.
<?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 of carry is 0
echo "Numbers: " . implode(", ", $numbers) . "
";
echo "Sum of Numbers: " . $sum . "
";
$words = ['Hello', 'World', 'PHP', 'Arrays'];
// Concatenate words into a single string
$sentence = array_reduce($words, function($carry, $item) {
return $carry . ($carry ? ' ' : '') . $item;
}, ''); // Initial value is an empty string
echo "Words: " . implode(", ", $words) . "
";
echo "Concatenated Sentence: " . $sentence . "
";
$products = [
['name' => 'Laptop', 'price' => 1200],
['name' => 'Mouse', 'price' => 25],
['name' => 'Keyboard', 'price' => 75],
];
// Calculate the total price of all products
$totalPrice = array_reduce($products, function($carry, $product) {
return $carry + $product['price'];
}, 0);
echo "Products:
";
print_r($products);
echo "Total Price of Products: $" . $totalPrice . "
";
?>
How it works: The `array_reduce()` function is used to iterate over an array and reduce it to a single value using a callback function. The callback receives an accumulator (`$carry`) and the current item (`$item`). It returns the updated accumulator, which is then passed to the next iteration. An optional initial value can be provided for the accumulator. This is perfect for tasks like summing, concatenating, or performing complex aggregations.