chocopi Posted July 27, 2007 Share Posted July 27, 2007 How do you go about adding all the values from a while loop. Here is my code: <?php $query = mysql_query("SELECT * FROM `Enemies` WHERE location='$location'") or die(mysql_error()); $num_row = mysql_num_rows($query) or die(mysql_error()); while($row = mysql_fetch_assoc($query)) { $rarity = $row['rarity']; $value = $rarity/100; $value2 = $value*$num_row; } ?> So this code would loop through 3 times for example and I would like to add up all of the $value2's. Now I know there is a way to do this, but I can't remember I think its along the line of $value2[0]+$value2[1]+$value2[2] or something like that, but as I said I can't remember. If you can help it would be much appreciated, Many Thanks, ~ Chocopi Quote Link to comment Share on other sites More sharing options...
DeepakJ Posted July 27, 2007 Share Posted July 27, 2007 Do a foreach loop, much easier when working with arrays since its length corresponds with array length. Quote Link to comment Share on other sites More sharing options...
DeepakJ Posted July 27, 2007 Share Posted July 27, 2007 like $counter = 0 foreach($array as $key => $value){ $counter = $value + $counter } Quote Link to comment Share on other sites More sharing options...
chocopi Posted July 27, 2007 Author Share Posted July 27, 2007 Cheers, but can you please show me how to use it with my code, seeing as I have never got around to learning foreach. I sound like such a n00b. I really should know this, how embarassing Thanks, ~ chocopi Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted July 27, 2007 Share Posted July 27, 2007 <?php $query = mysql_query("SELECT * FROM `Enemies` WHERE location='$location'") or die(mysql_error()); $num_row = mysql_num_rows($query) or die(mysql_error()); $value2 = 0;//set it to 0 incase it was used before in your script - also means the variable is defined. while($row = mysql_fetch_assoc($query)) { $rarity = $row['rarity']; $value = $rarity/100; $value2 += $value*$num_row;//using the += operator works out $valeu*$num_row and adds it onto the current value of $value2. This allows you to add them all up } echo $value2; ?> Quote Link to comment Share on other sites More sharing options...
chocopi Posted July 27, 2007 Author Share Posted July 27, 2007 Cheers GingerRobot That works a treat, I knew it was easy And thanks DeepakJ for your help ~ Chocopi Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.