Sum of a row of an associative array using PHP?

20,791

Solution 1

To get the sum based on a certain column key, use this:

array_sum(array_column($assoc_array, 'key_name'));

Solution 2

array_sum will work for you.

$arr = array(
     'key1' => 54.3,
     65 => 10
);
$sum = array_sum($arr);

Solution 3

According to alex's post, you can use array_column() only if you're using PHP >= 5.5!

If you can't change the PHP-Version and your PHP-Version is lower than 5.5, you could also go for:

array_sum(array_map(function($element){return $element['key_name'];}, $assoc_array));

this will results the same.

Solution 4

array_sum http://php.net/array_sum

It sums an array - regardless of index type.

Share:
20,791
NickKampe
Author by

NickKampe

http://nickkampe.com

Updated on July 09, 2022

Comments

  • NickKampe
    NickKampe almost 2 years

    Is there a php function that returns the sum of a row of an associative array?

    If not should I just use a counter and a foreach loop?

    Appreciate it!

  • Dwza
    Dwza about 9 years
    sometimes there are unvoted answeres that are actually the best ones... thx for this... i was looking for some like this. +1 from here ;)