PHP

PHP Aggregate Array with array_reduce

Master PHP's `array_reduce` to efficiently aggregate array values, perform complex calculations, or build new data structures. A powerful functional tool.

// Calculate total sum of prices from an array of products
$products = [
    ['name' => 'Laptop', 'price' => 1200, 'quantity' => 1],
    ['name' => 'Mouse', 'price' => 25, 'quantity' => 2],
    ['name' => 'Keyboard', 'price' => 75, 'quantity' => 1]
];

$totalOrderValue = array_reduce($products, function($carry, $item) {
    return $carry + ($item['price'] * $item['quantity']);
}, 0);

echo "Total Order Value: " . $totalOrderValue . "

";
/* Expected Output for totalOrderValue:
Total Order Value: 1325
*/

// Transform an array into an associative array indexed by 'name'
$indexedProducts = array_reduce($products, function($carry, $item) {
    $carry[$item['name']] = $item;
    return $carry;
}, []);

echo "Indexed Products:
";
print_r($indexedProducts);
/* Expected Output for indexedProducts:
Indexed Products:
Array
(
    [Laptop] => Array
        (
            [name] => Laptop
            [price] => 1200
            [quantity] => 1
        )

    [Mouse] => Array
        (
            [name] => Mouse
            [price] => 25
            [quantity] => 2
        )

    [Keyboard] => Array
        (
            [name] => Keyboard
            [price] => 75
            [quantity] => 1
        )

)*/
How it works: The `array_reduce` function iterates over an array, passing the value of each element to a callback function, along with an 'accumulator' (the `$carry` variable). The callback's return value is then passed as the `$carry` argument in the next iteration. This allows for powerful aggregations (like summing or averaging), or transformations (like re-indexing an array), reducing the entire array to a single, cumulative result or a new structured array. It's a fundamental functional programming concept for data manipulation.

Need help integrating this into your project?

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

Hire DigitalCodeLabs