PHP

Aggregate PHP Array Values to a Single Result

Master `array_reduce()` to iterate through an array and progressively build a single result, like a sum, concatenation, or complex object, using a callback function.

<?php
$numbers = [1, 2, 3, 4, 5];

// Calculate the sum of all numbers
$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0); // 0 is the initial value of $carry

echo "Sum: " . $sum . "
"; // Output: Sum: 15

$words = ['Hello', 'World', 'PHP', 'Arrays'];

// Concatenate words with spaces
$sentence = array_reduce($words, function($carry, $item) {
    return $carry === '' ? $item : $carry . ' ' . $item;
}, ''); // Initial value is an empty string

echo "Sentence: " . $sentence . "
"; // Output: Sentence: Hello World PHP Arrays

$cartItems = [
    ['item' => 'Laptop', 'price' => 1200, 'qty' => 1],
    ['item' => 'Mouse', 'price' => 25, 'qty' => 2],
    ['item' => 'Keyboard', 'price' => 75, 'qty' => 1]
];

// Calculate total cart value
$totalValue = array_reduce($cartItems, function($carry, $item) {
    return $carry + ($item['price'] * $item['qty']);
}, 0);

echo "Total Cart Value: $" . $totalValue . "
"; // Output: Total Cart Value: $1325
?>
How it works: `array_reduce()` iteratively reduces the array to a single value using a callback function. The callback receives two arguments: the `carry` (the accumulated value from the previous iteration or the initial value) and the current `item` from the array. This is extremely powerful for performing aggregations, building new data structures, or processing an array into a single result.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs