Sum of associative array string using PHP?

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

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

Appreciate it!

+5
source share
4 answers

array_sum will work for you.

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

To get the amount based on a specific column, use this:

array_sum(array_column($assoc_array, 'key_name'));
+20
source
+2

alex, array_column(), PHP >= 5.5

PHP-, PHP- 5.5, :

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

.

+2

All Articles