Welcome to WebmasterWorld Guest from 54.197.94.141

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

adding numbers in a foreach loop

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

5+ 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
4:25 pm on Mar 3, 2010 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



$total = 0;
foreach($myArray as $value){
if(is_numeric($value)){
$total += $value;
}
}
echo $total;
4:28 pm on Mar 3, 2010 (gmt 0)

WebmasterWorld Senior Member topr8 is a WebmasterWorld Top Contributor of All Time 10+ Year Member



$total=0;
foreach($myArray as $key => $value){
$amount = $myArray[$key];
echo $amount;
$total += $amount;
}
echo $total;
4:29 pm on Mar 3, 2010 (gmt 0)

WebmasterWorld Senior Member topr8 is a WebmasterWorld Top Contributor of All Time 10+ Year Member



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

WebmasterWorld Senior Member eelixduppy is a WebmasterWorld Top Contributor of All Time 5+ Year Member



This can all be shortened to:

$total = array_sum($myArray);


;)

[us.php.net...]