Php循环 - 相同的循环递增然后递减

时间:2015-08-25 21:19:17

标签: php loops

所以我目前的代码就是这样:

<?php 
$x=1;
 while($x<=512)
{
    echo $x.'<br>';
    $x=$x*2;
}
while($x>=1)
{
    echo $x.'<br>';
    $x=$x/2;
 }
?>
  

结果就是这样:   
1   
2   
4   
8   
16   
32   
64   
128   
256   
512   
1024   
512   
256   
128   
64   
32   
16   
8   
4   
2   
1

但是我想要做的是将一个循环与currnet两个相关联 'while'循环当前是。我想知道在PHP中的同一个循环中是否有一种方法可以同时使用Increment和Decrement?如果是这样,请解释如何使用代码段并解释。谢谢。

3 个答案:

答案 0 :(得分:0)

你可以这样做,但我没有看到它的实用性。

Exp question 1 :  
 excel
 sun 
 Microsystem ....

My result that I know : 
excel
sun
Microsystem ....

Exp question 2 :
Tel: 08 89 98 34 84 

My result that I know : 
0889983484 

答案 1 :(得分:0)

这就是我所说的。仍然保持循环的while部分与你拥有的相同。只需增加/减少并将输出保存到另一个变量,以便稍后回显。

<?php
$x = 1;
$y = 1024;
$outputX = '';
$outputY = '';

while($x <= 512){
    $outputX .= "{$x}<br>";
    $outputY .= "{$y}<br>";

    $x *= 2;
    $y /=2;

}

echo $outputX;
echo $outputY;
//need to output the last value of $y because the loop misses the last iteration of the second while loop.
echo $y;

答案 2 :(得分:0)

测试是否已达到上限。如果是,请执行除法代码。

$x=1;
$reverse = 0;
 while($x<=1025 && $x>=1)
{
    echo $x.'<br>';
    if($x == 1024){ $reverse= 1;}
    if($reverse == 0) {
        $x=$x*2;
    } else {
        $x=$x/2;       
    }
}