Jump to content

[SOLVED] Adding values from while loop


chocopi

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/62085-solved-adding-values-from-while-loop/
Share on other sites

<?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;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.