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!
asked May 18, 2010 at 1:10
1
To get the sum based on a certain column key, use this:
array_sum[array_column[$assoc_array, 'key_name']];
answered Sep 4, 2014 at 17:52
alexalex
9362 gold badges9 silver badges11 bronze badges
1
array_sum will work for you.
$arr = array[
'key1' => 54.3,
65 => 10
];
$sum = array_sum[$arr];
answered May 18, 2010 at 1:12
Tim CooperTim Cooper
153k37 gold badges320 silver badges272 bronze badges
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.
answered Feb 27, 2015 at 23:02
DwzaDwza
6,4174 gold badges38 silver badges69 bronze badges
array_sum
//php.net/array_sum
It sums an array - regardless of index type.
answered May 18, 2010 at 1:12
Mitch DempseyMitch Dempsey
37.5k6 gold badges65 silver badges73 bronze badges
[PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8]
array_sum — Calculate the sum of values in an array
Description
array_sum[array $array
]: int|float
Parameters
array
The input array.
Return Values
Returns the sum of values as an integer or float; 0
if the array
is empty.
Examples
Example #1 array_sum[] examples
The above example will output:
rodrigo at adboosters dot com ¶
7 months ago
If you want to calculate the sum in multi-dimensional arrays:
Example:
samiulmomin191139 at gmail dot com ¶
7 months ago
444 ¶
6 months ago
$total = 0;
foreach [$array as $key => $value]{
$total += $value;
}
Print "sum $total";