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.
Comments
-
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 about 9 yearssometimes there are unvoted answeres that are actually the best ones... thx for this... i was looking for some like this. +1 from here ;)