30
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.

1
  • 1
    Just initialize a variable to 0 outside the loop, and add each $value to it inside the loop. Seriously, this is a really elementary general beginner programming question; make sure you're clear on the real basic concepts before you try to go farther, since otherwise you're going to encounter a lot of things that won't make sense to you. Commented May 14, 2013 at 8:07

5 Answers 5

104
$sum = 0;
foreach($group as $key=>$value)
{
   $sum+= $value;
}
echo $sum;
Sign up to request clarification or add additional context in comments.

Comments

24

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

Comments

7

You can use array_sum().

$total = array_sum($group);

2 Comments

I can imagine someone hasn't upvoted this. Everyone seems to be reinventing the wheel
To be fair, the algorithm is so trivial sometimes people forget that things like this exist in the standard library. Sometimes SO gets locked into a mob mentality, up voting answers while ignoring others because the first one works.
5

Use +=

$val = 0;

foreach($arr as $var) {
   $val += $var; 
}

echo $val;

1 Comment

This is definitely the best answer if not using "as value" in your foreach!
0
$total=0;
foreach($group as $key=>$value)
{
   echo $key. " = " .$value. "<br>"; 
   $total+= $value;
}
echo $total;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.