Forum Moderators: coopster

Message Too Old, No Replies

adding numbers in a foreach loop

         

ahmed24

4:16 pm on Mar 3, 2010 (gmt 0)

10+ Year Member



i've got a foreach loop and inside the foreach loop i have echo $amount, which gives me seperate numbers from an array.

can anyone tell me how i can add these numbers up so that i can get the total?

my code currently looks like this:


foreach($myArray as $key => $value){
$amount = $myArray[$key];
echo $amount;
}


problem with this code is that i get all the numbers from the array. but i would like to add them up to get a total sum

Readie

4:25 pm on Mar 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



$total = 0;
foreach($myArray as $value){
if(is_numeric($value)){
$total += $value;
}
}
echo $total;

topr8

4:28 pm on Mar 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



$total=0;
foreach($myArray as $key => $value){
$amount = $myArray[$key];
echo $amount;
$total += $amount;
}
echo $total;

topr8

4:29 pm on Mar 3, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



:)

eelixduppy

4:38 pm on Mar 3, 2010 (gmt 0)



This can all be shortened to:

$total = array_sum($myArray);


;)

[us.php.net...]