I have seen various posted about this question so am aware some answers to this may exist. however I am none the wiser after reading these.
I have an array that is
You can do this using array_map() and select the vatAmount
column first:
$totalVatAmount = array_sum(array_map(function($account_invoices) {
return $account_invoices['vatAmount'];
}, $account_invoices));
Of course, internally this performs a double loop; it's just that you don't see it inside the code. If you use array_reduce() then you can get rid of one loop:
$totalVatAmount = array_reduce($account_invoices,
function($totalAmount, $item) {
$totalAmount += $item['vatAmount'];
return $totalAmount;
},
0
);
However, if speed is the only interest, you should use foreach
. Because there is no function calls used to calculate the final sum. This solution is faster than other solution.
$totalVatAmount = 0;
foreach ($account_invoices as $item) {
$totalVatAmount += $item['vatAmount'];
}