简体   繁体   English

如何在php中计算逆?

[英]How to count inverse with for in php?

My Problem: I want to count inverse in the for loop. 我的问题:我想在for循环中计算倒数。

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). 如果我把$i--不起作用(我的服务器崩溃)。

Help meeee! 帮帮我吧!

Best Regards, Adam 最诚挚的问候,亚当

When you say $i-- crashes your server, did you change the initialization and condition for $i ? 当你说$i--崩溃你的服务器时,你是否更改了$i的初始化和条件?

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

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. 如果走for ,你写的,只是更换$i++$i--价值$i将每一次迭代(1,0,-1,-2,等)和循环条件递减$i<=10总是如此。

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;
}

I don't get it, just doing 我不明白,只是这样做

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

is not enough? 是不足够的?

from the PHP manual 来自PHP手册

for (expr1; expr2; expr3) statement for(expr1; expr2; expr3)语句

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop. 第一个表达式(expr1)在循环开始时无条件地计算(执行)一次。

In the beginning of each iteration, expr2 is evaluated. 在每次迭代开始时,将评估expr2。 If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. 如果它的计算结果为TRUE,则循环继续并执行嵌套语句。 If it evaluates to FALSE, the execution of the loop ends. 如果计算结果为FALSE,则循环的执行结束。

At the end of each iteration, expr3 is evaluated (executed). 在每次迭代结束时,评估(执行)expr3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM