Search code examples
phparraysmultidimensional-arrayarray-sum

Sum the values in a column of a 2d array


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

Solution

  • Just a way to do it:

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