php 在foreach循环php中求和值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16535630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum values in foreach loop php
提问by bob
foreach($group as $key=>$value)
{
echo $key. " = " .$value. "<br>";
}
For example:
例如:
doc1 = 8
doc2 = 7
doc3 = 1
文档 1 = 8
文档 2 = 7
文档 3 = 1
I want to count $value, so the result is 8+7+1 = 16. What should i do?
我想计算$value,所以结果是8+7+1 = 16。我该怎么办?
Thanks.
谢谢。
回答by chandresh_cool
$sum = 0;
foreach($group as $key=>$value)
{
$sum+= $value;
}
echo $sum;
回答by Kishan Patel
In your case IF you want to go with foreach loop than
在您的情况下,如果您想使用 foreach 循环而不是
$sum = 0;
foreach($group as $key => $value) {
$sum += $value;
}
echo $sum;
But if you want to go with direct sum of array than look on below for your solution :
但是,如果您想使用数组的直接求和,请不要在下面查看您的解决方案:
$total = array_sum($group);
for only sum of arraylooping is time wasting.
因为只有数组循环的总和是浪费时间。
http://php.net/manual/en/function.array-sum.php
http://php.net/manual/en/function.array-sum.php
array_sum — Calculate the sum of values in an array
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";
?>
The above example will output:
上面的例子将输出:
sum(a) = 20
sum(b) = 6.9
回答by Mr. Alien
Use +=
用 +=
$val = 0;
foreach($arr as $var) {
$val += $var;
}
echo $val;
回答by Austin Brunkhorst
回答by Suhel Meman
$total=0;
foreach($group as $key=>$value)
{
echo $key. " = " .$value. "<br>";
$total+= $value;
}
echo $total;