是否有一个简单的逻辑来实现for循环,取决于分隔符?
if $a>b for($i=a; $i>b; $i--)
else for($i=a; $i<b; $i++)
但我需要在一个循环中完成我不能做类似的事情
$start = $a<$b? $a : $b;
因为我需要循环始终从开始$a
并走向$b
,也许还有另一种方式?我可以有理由拒绝投票吗?我的问题还不清楚,如果您不理解问题,请不要触摸它。
Hope this helps
$inc = $a < $b ? 1: -1;
for ($i = $a; $i != $b; $i += $inc) {
/* some code here */
}
Explanation:
First step is estimation of the increment meaning whether to increment or decrement $a to reach $b.
Obviously if $a < $b then increment needed or else decrement. $i += $inc is the generic statement that adds +1 or -1. Adding +1 is increment and adding -1 is decrement.
Ultimately the loop exit condition is $i != $b, hoping this condition will be met atleast once in the increment/decrement.
Your question contains some logical error. Although syntax is correct.
if $a<b for($i=a; $i>b; $i--)
Here, $a
is smaller than b
and in for
loop you give condition $i>b
which will never meet because $i
and $a
are already smaller than b
. So, this loop will not run even for a single time. This is also same for else
because here also loop will not execute for a single time.
Is that you want..?