PHP

Calculate Sum of Specific Property in Array of Associative Arrays

Efficiently sum values of a particular property across an array of associative arrays or objects in PHP using `array_reduce`, ideal for reporting or aggregation.

<?php
$products = [
    ['item' => 'Laptop', 'price' => 1200, 'quantity' => 2],
    ['item' => 'Mouse', 'price' => 25, 'quantity' => 5],
    ['item' => 'Keyboard', 'price' => 75, 'quantity' => 3],
];

// Calculate total price of all products (price * quantity)
$totalRevenue = array_reduce($products, function ($carry, $product) {
    return $carry + ($product['price'] * $product['quantity']);
}, 0);

// $totalRevenue will be (1200*2) + (25*5) + (75*3) = 2400 + 125 + 225 = 2750
echo "Total Revenue: $" . $totalRevenue . "
";

// Calculate total quantity
$totalQuantity = array_reduce($products, function ($carry, $product) {
    return $carry + $product['quantity'];
}, 0);
echo "Total Quantity: " . $totalQuantity . "
";
?>
How it works: This snippet demonstrates how to use `array_reduce` to calculate an aggregated value (like a sum) from an array of associative arrays. It iterates through the array, applying a callback function that accumulates a result. In this example, it calculates the total revenue by multiplying price and quantity for each product, and also the total quantity of all items, providing a concise way to perform aggregations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs