Sum values in foreach loop php

26

foreach($group as $key=>$value)
{
    echo $key. " = " .$value. "<br>";
}

For example:

doc1 = 8

doc2 = 7

doc3 = 1

I want to count $value, so the result is 8+7+1 = 16. What should i do?

Thanks.

This question is tagged with php foreach count

~ Asked on 2013-05-14 05:17:58

The Best Answer is


92

$sum = 0;
foreach($group as $key=>$value)
{
   $sum+= $value;
}
echo $sum;

~ Answered on 2013-05-14 05:27:59


17

In your case IF you want to go with foreach loop than

$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 array looping is time wasting.

http://php.net/manual/en/function.array-sum.php

array_sum — Calculate the sum of values in an array

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

~ Answered on 2013-05-14 05:26:01


Most Viewed Questions: