I have a multidimensional array as follows:
Array(
[0] => Array
(
[name] => item 1
[quantity] => 2
[price] => 20.00
)
[1] => Array
(
[name] => item 2
[quantity] => 1
[price] => 15.00
)
[2] => Array
(
[name] => item 3
[quantity] => 4
[price] => 2.00
)
)
I need the 'grand total' of all these items. Now clearly I could get these by doing the following:
$grand_total = 0;
foreach ($myarray as $item) {
$grand_total += $item['price'] * $item['quantity'];
}
echo $grand_total;
My question is - can this be done in less lines of code using any of the array functions in PHP?
no. you would have to define a callback function to use array_reduce
. this would even get longer but make the code better reusable.
EDIT: Didn't write PHP for a long time but this should do it:
function sum_total_price_of_items($sum, $item) {
return $sum + $item['price'] * $item['quantity']
}
echo array_reduce($myarray, "sum_total_price_of_items", 0)
If you are using PHP >= 5.3 (needed for lambda functions), then the array_reduce
solution would be shorter:
$input = array(
array(
'name' => 'item 1',
'quantity' => '2',
'price' => 20.00,
),
array(
'name' => 'item 2',
'quantity' => '1',
'price' => 15.00,
),
array(
'name' => 'item 3',
'quantity' => '4',
'price' => 2.00,
),
);
$total = array_reduce($input,
function($subtotal, $row) {
return $subtotal + $row['quantity'] * $row['price'];
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With