PHP
Aggregating PHP Array Data with array_reduce
Understand how to iterate through a PHP array and reduce it to a single value (e.g., sum, concatenation) by repeatedly applying a callback function with array_reduce() for powerful 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);
echo "Sum: " . $sum . "
";
// Expected output: Sum: 15
$words = ['Hello', 'World', 'PHP', 'Arrays'];
// Concatenate words into a single string
$sentence = array_reduce($words, function($carry, $item) {
return $carry . ($carry ? ' ' : '') . $item;
}, '');
echo "Sentence: " . $sentence . "
";
// Expected output: Sentence: Hello World PHP Arrays
$products = [
['name' => 'Laptop', 'price' => 1200, 'quantity' => 2],
['name' => 'Mouse', 'price' => 25, 'quantity' => 5],
['name' => 'Keyboard', 'price' => 75, 'quantity' => 1]
];
// Calculate total value of all products
$totalValue = array_reduce($products, function($carry, $product) {
return $carry + ($product['price'] * $product['quantity']);
}, 0);
echo "Total value: $" . $totalValue . "
";
// Expected output: Total value: $2425
?>
How it works: The `array_reduce()` function is used to reduce an array to a single value. It iterates through the array, passing the 'carry' value (the result from the previous iteration) and the current item to a callback function. The initial value for 'carry' can be provided as the third argument. This is powerful for tasks like summing numbers, concatenating strings, or calculating complex aggregates from array data.