Sum of a row of an associative array using PHP? Sum of a row of an associative array using PHP? arrays arrays

Sum of a row of an associative array using PHP?


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

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


array_sum will work for you.

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


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.