Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'])
like image 372
Mr Sorbose Avatar asked Oct 11 '12 11:10

Mr Sorbose


People also ask

How do you sum all column values in a multidimensional array?

You could use the aggregate function SUM to get the sum of all the f_count directly in your query. You would combine this with $stmt->fetchColumn() to get the value of the first column (which would be the sum) of the first row (which will be the only row since we used an aggregate function).

What is multidimensional associative array?

PHP Multidimensional array is used to store an array in contrast to constant values. Associative array stores the data in the form of key and value pairs where the key can be an integer or string. Multidimensional associative array is often used to store data in group relation.

How do I sum an array of numbers in PHP?

The array_sum() function returns the sum of all the values in an array(one dimensional and associative). It takes an array parameter and returns the sum of all the values in it. The only argument to the function is the array whose sum needs to be calculated.


3 Answers

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')); 
like image 184
Blablaenzo Avatar answered Nov 02 '22 14:11

Blablaenzo


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));
like image 34
Khior Avatar answered Nov 02 '22 14:11

Khior


Just a way to do it:

$sum = 0;

foreach($account_invoices as $num => $values) {
    $sum += $values[ 'vatAmount' ];
}
like image 28
matthias Avatar answered Nov 02 '22 13:11

matthias