Welcome to WebmasterWorld Guest from 23.22.231.22

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)

Junior Member

5+ Year Member

joined:July 17, 2006
posts:137
votes: 0


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)

Senior Member

WebmasterWorld Senior Member 5+ Year Member

joined:Dec 13, 2009
posts:943
votes: 0


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

Senior Member

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

joined:Apr 19, 2002
posts:3171
votes: 8


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

Senior Member

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

joined:Apr 19, 2002
posts:3171
votes: 8


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

Senior Member

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

joined:Nov 12, 2005
posts:5966
votes: 0


This can all be shortened to:

$total = array_sum($myArray);


;)

[us.php.net...]