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

Recommended Answers

All 3 Replies

how u insert the value in $total variable.
from any form or from database?

please describe briefly.

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;
Member Avatar for diafol

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.