array_sum
(PHP 4 >= 4.0.4, PHP 5)
array_sum — Calculate the sum of values in an array
Parameters
-
array
-
The input array.
Return Values
Returns the sum of values as an integer or float.
Changelog
Version | Description |
---|---|
4.2.1 | PHP versions prior to 4.2.1 modified the passed array itself and converted strings to numbers (which most of the time converted them to zero, depending on their value). |
Examples
Example #1 array_sum() examples
<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>
The above example will output:
sum(a) = 20 sum(b) = 6.9
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения, относящиеся к переменным и типам
- Массивы
- array_change_key_case
- array_chunk
- array_column
- array_combine
- array_count_values
- array_diff_assoc
- array_diff_key
- array_diff_uassoc
- array_diff_ukey
- array_diff
- array_fill_keys
- array_fill
- array_filter
- array_flip
- array_intersect_assoc
- array_intersect_key
- array_intersect_uassoc
- array_intersect_ukey
- array_intersect
- array_key_exists
- array_keys
- array_map
- array_merge_recursive
- array_merge
- array_multisort
- array_pad
- array_pop
- array_product
- array_push
- array_rand
- array_reduce
- array_replace_recursive
- array_replace
- array_reverse
- array_search
- array_shift
- array_slice
- array_splice
- array_sum
- array_udiff_assoc
- array_udiff_uassoc
- array_udiff
- array_uintersect_assoc
- array_uintersect_uassoc
- array_uintersect
- array_unique
- array_unshift
- array_values
- array_walk_recursive
- array_walk
- array
- arsort
- asort
- compact
- count
- current
- each
- end
- extract
- in_array
- key_exists
- key
- krsort
- ksort
- list
- natcasesort
- natsort
- next
- pos
- prev
- range
- reset
- rsort
- shuffle
- sizeof
- sort
- uasort
- uksort
- usort
Коментарии
If you want to calculate the sum in multi-dimensional arrays:
<?php
function array_multisum(array $arr): float {
$sum = array_sum($arr);
foreach($arr as $child) {
$sum += is_array($child) ? array_multisum($child) : 0;
}
return $sum;
}
?>
Example:
<?php
$data =
[
'a' => 5,
'b' =>
[
'c' => 7,
'd' => 3
],
'e' => 4,
'f' =>
[
'g' => 6,
'h' =>
[
'i' => 1,
'j' => 2
]
]
];
echo array_multisum($data);
//output: 28
?>
array_sum() doesn't "ignore strings if they are not convertible", it converts them to zero. array_product() does the same thing, where the difference between "ignoring" and "converting to zero" is much more obvious.