How to read the reverse with for in php?

My problem: I want to count the reverse in a for loop.

This is the opposite of what I want to do:

for($i=1;$i<=10;$i++){ echo $i; } 

If I put $i-- , then it does not work (my server crashes).

Help!

Best regards, Adam

+6
loops php count inverse
source share
4 answers

When you say that $i-- your server failed, did you change the initialization and condition for $i ?

 for($i=10; $i>=1; $i--){ echo $i; } 
+23
source share

If you take for , as you wrote, and simply replace $i++ with $i-- , the value of $i will decrease with each iteration (1, 0, -1, -2, etc.), and the loop condition $i<=10 always true.

If you want to count back, you also need to change other parts (initialization and looping condition):

 for ($i=10; $i>=1; $i--){ echo $i; } 

Or you take the last one and subtract the current value from it and add the first value to it:

 for ($first=1, $i=$first, $last=10; $i<=$last; $i++){ echo $last - $i + $first; } 
+6
source share

I don't understand, just doing

 for($i=10;$i>=1;$i--){ echo $i; } 

not enough?

+2
source share

from PHP manual

for (expr1; expr2; expr3) Statement

The first expression (expr1) is evaluated (executed) unconditionally at the beginning of the loop.

At the beginning of each iteration, expr2 is computed. If it evaluates to TRUE, the loop continues and the nested statement (s) is executed. If it evaluates to FALSE, the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

+1
source share

All Articles