View Full Version : Reverse a Loop

03-10-2008, 04:25 AM
I'm currently using the following code as a loop:

for ($counter = 0; $counter <= $Points; $counter += 1)

How many times it loops is based on user input. For example, if the user enters 60 (in the affecting field), it will loop a formula, starting at zero and stopping at sixty. However, I would like to have it start at sixty and go backwards and stop at zero. I've tried playing around with the values in the above code, but I always either [a] get an error, [b] get an infinite loop, or [c] get positive sixty all of the way to negative sixty.

Thanks in advance.

03-10-2008, 04:56 AM
for ($counter = 60; $counter >= 0; $counter--)

Going with your example, is points = 60?

03-10-2008, 04:58 AM
Technically, my above example will run 61 times. You can change >= to >.

03-10-2008, 08:09 PM
I've tried that before, but 60 is just an example and is actually determined based on user input. I've tried setting it equal to a variable, but that always results in an error.

03-11-2008, 01:26 AM
I realize that 60 is a variable. What I didn't know was the variable name. Thats why I was asking if $points was the variable name. If so, you'd simply replace the 60 in my above code with $points.

//this code will run 60 times.
$points = 60;
for ($i=$points; $i > 0; $i--) {
echo $i . "\n";

If you're getting an error, it would be helpful to know the exact error you're receiving.