multidimensional array array_sum

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 like the following.

[0] => Array
    (
        [id] => 95659865986
        [invoiceNumber] => 6374324
        [invoiceTitle] => Monthly
        [invoiceStatus] => Paid
        [accountId] => 6235218753
        [totalExVat] => 158.95
        [dateCreated] => 1 Apr 2012
        [vatAmount] => 20.00
    )

All I wish to do is do array sum on the vatAmount values of this array.

As the following doesnt seem to be doing much.

(array_sum($account_invoices['vatAmount'])

Answers


Just a way to do it:

$sum = 0;

foreach($account_invoices as $num => $values) {
    $sum += $values[ 'vatAmount' ];
}

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'));

I would use array_map to reduce the array to only what is needed. Bear in mind, this will only work with PHP 5.3 onwards.

$total_vat = array_sum( array_map(
                 function($element){
                     return $element['vatAmount'];
                 }, 
             $account_invoices));

You could use array_map first to collect the vatAmout value.

$sum = array_sum(array_map(function($var) {
  return $var['vatAmout'];
}, $account_invoices));

A way to do this using a PHP 5.3+ anonymous function

$account_invoices = array(
    0 => array(
        'id' => '95659865986',
        'invoiceNumber' => '6374324',
        'invoiceTitle' => 'Monthly',
        'invoiceStatus' => 'Paid',
        'accountId' => '6235218753',
        'totalExVat' => 158.95,
        'dateCreated' => '1 Apr 2012',
        'vatAmount' => 20.00
    ),
    1 => array(
        'id' => '95659865987',
        'invoiceNumber' => '6374325',
        'invoiceTitle' => 'Monthly',
        'invoiceStatus' => 'Paid',
        'accountId' => '6235218753',
        'totalExVat' => 208.95,
        'dateCreated' => '1 May 2012',
        'vatAmount' => 25.00
    ),
);


$sumDetail = 'vatAmount';
$totalVAT = array_reduce($account_invoices,
           function($runningTotal, $record) use($sumDetail) {
               $runningTotal += $record[$sumDetail];
               return $runningTotal;
           },
           0
);
echo $totalVAT;

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'];
}

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);

Just another way to do this using array_reduce:

$vatMount = array_reduce($account_invoices, function($total, $value) {
    return $total + $value['vatAmount'];
});

Need Your Help

How do I get the current version of my iOS project in code?

ios objective-c iphone swift

I would like to be able to get the current version of my iOS project/app as an NSString object without having to define a constant in a file somewhere. I don't want to change my version value in 2 ...

How to open the Chrome Developer Tools in a new window?

google-chrome google-chrome-devtools

When I try to use the Chrome Developer Tools, it seems I can no longer view it in a new window.