homepage Welcome to WebmasterWorld Guest from 54.166.95.146
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
adding numbers in a foreach loop
ahmed24




msg:4090776
 4:16 pm on Mar 3, 2010 (gmt 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

 

Readie




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

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

topr8




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

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

topr8




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

:)

eelixduppy




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

This can all be shortened to:

$total = array_sum($myArray);

;)

[us.php.net...]

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved