How to count inverse with for in php?

╄→尐↘猪︶ㄣ 提交于 2019-12-18 15:55:30

问题


My Problem: I want to count inverse in the for loop.

This is the opposite of what I want to do:

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

If I put $i-- doesn't works (my server crashes).

Help meeee!

Best Regards, Adam


回答1:


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

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



回答2:


If you take the for as you wrote and just replace $i++ with $i--, the value of $i will be decremented with every iteration (1, 0, -1, -2, etc.) and the looping condition $i<=10 is always true.

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

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

Or you take the last 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;
}



回答3:


I don't get it, just doing

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

is not enough?




回答4:


from the PHP manual

for (expr1; expr2; expr3) statement

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

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

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



来源:https://stackoverflow.com/questions/3167580/how-to-count-inverse-with-for-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!