Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum values in foreach loop php [closed]

Tags:

foreach

php

count

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.

like image 638
bob Avatar asked May 14 '13 05:05

bob


People also ask

How do you do foreach loop addition?

$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);

How do you sum in PHP?

array_sum() function in PHP The array_sum() function returns the sum of the values in an array. The returned value can be integer or float. It returns 0 if the array is empty.

Does Break stop foreach?

break ends execution of the current for , foreach , while , do-while or switch structure.


1 Answers

$sum = 0; foreach($group as $key=>$value) {    $sum+= $value; } echo $sum; 
like image 68
chandresh_cool Avatar answered Sep 22 '22 06:09

chandresh_cool