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
Just a way to do it:
$sum = 0;
foreach($account_invoices as $num => $values) {
$sum += $values[ 'vatAmount' ];
}
You could use array_map
first to collect the vatAmout
value.
$sum = array_sum(array_map(function($var) {
return $var['vatAmout'];
}, $account_invoices));
You can't do this directly with array_sum
, which would sum everything in the array.
You can do it with a loop:
$sum = 0;
foreach($items as $item)
$sum += $item['vatAmount'];
or you can filter the array (in this case it isn't very convenient, but if you had to calculate, say, S&H expenses plus VAT plus..., from each single item, and then sum...):
// Input: an array (element #n of array of arrays), output: VAT field
function getVAT($item)
{
return $item['vatAmount'];
}
// Array with all VATs
$vats = array_map('getVAT', $items);
$sum = array_sum($vats);
Also you can do this (if you like array_sum function):
foreach($account_invoices as $num => $values) {
$vatAmount[] = $values[ 'vatAmount' ];
}
$Total = array_sum($vatAmount);
array_sum_multidimensional Helper function
if (!function_exists('array_sum_multidimensional')) {
/**
* returns the sum of a element from an array of arrays
*/
function array_sum_multidimensional(array $array, $elementKey){
$sum = 0;
foreach($array as $key => $value) {
$sum += $value[ $elementKey ];
}
return $sum;
}
}
If you have PHP 5.5+ you can do this without looping or using a callback (since function calls are relatively expensive) ... just use:
$sum = array_sum(array_column($account_invoices, 'vatAmount'));