0

ok so i have been trying to think of a way that i could calculate multiple values under one variable.
ex:
in my loop i am calling $total a few times depending on how many entries there are. i know that if i was to echo $total it would only give me the last value. what i want to do it get all the $total's and add them together.

this might be really simple but i just done know how to do it.

thanks in advance

4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by diafol
0

in my loop i am calling $total

Not sure what kind of loop you have(for, while,...), but for illustration purposes, the code below uses a while

//initialize the variable outside the loop
$total=0;

//assuming I am retrieving data from a DB query result
//where one of the columns in the recordset is named "amount"
while( $row=mysql_fetch_assoc($rs) )
{
   //update the total within the while
   $total += $row['amount'];
}
echo $total;
0

Above correct for mysql values - if using non db values - pretty much the same:

$total = 0;
(start loop)
if(condition is true)$total += $value_to_add;
(end loop)

loop is optional

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.