PHP 8.3.0 RC 6 available for testing

array_sum

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

array_sum 对数组中所有值求和

说明

array_sum(array $array): int|float

array_sum() 将数组中的所有值相加,并返回结果。

参数

array

输入的数组。

返回值

所有值的和以整数或浮点数的结果返回,array 为空时则返回 0

示例

示例 #1 array_sum() 例子

<?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";
?>

以上示例会输出:

 
sum(a) = 20
sum(b) = 6.9

add a note

User Contributed Notes 6 notes

up
15
rodrigo at adboosters dot com
1 year ago
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
?>
up
1
Michele Marsching
10 months ago
Notably the function converts strings to float and ignores strings if they are not convertable:

<?php
$a
= array("String", 2, 4, 6, 8);
echo
"sum(a) = " . array_sum($a) . "\n";

$b = array("12.3456", 2, 4, 6, 8);
echo
"sum(b) = " . array_sum($b) . "\n";
?>

sum(a) = 20
sum(b) = 32.3456
up
-1
sarosekvlad12 at gmail dot com
5 months ago
If you have a case where your array has int in strings, it sums them up as if there were only int in the array!
function sum_mix($a)
{
return array_sum($a);
}
var_dump(sum_mix([9, 3, '7', '3']));
Response will be int(22)
up
-3
harl at gmail dot com
10 months ago
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.
up
-9
samiulmomin191139 at gmail dot com
1 year ago
<?php
//you can also sum multidimentional arrays like this;

function arraymultisum(array $arr){
$sum=null;

foreach(
$arr as $child){
$sum+=is_array($child) ? arraymultisum($child):$child;
}
return
$sum;
}

echo
arraymultisum(array(1,4,5,[1,5,8,[4,5,7]]));

//Answer Will be
//40

?>
up
-17
yakushabb at gmail dot com
1 year ago
array_sum converts strings to integer and array_sum(2,'2') returns 4.

I had no idea.
To Top