2016-08-14 289 views
-4

嗨学习考试,并有此循环。PHP for循环while while循环

<?php 
$ab = 0; 
$xy = 1; 

echo "<table>"; 

for ($i = 0; $i < 5; $i++) {  
    echo "<tr>";  

    echo "<td>" . $ab . "</td><td>" . $xy . "</td>"; 
    $ab += $xy;  $xy += $ab;  

    echo "</tr>"; 
} 
echo "</table>"; 

现在的问题是,我该如何将其重写为while循环?要记住的是,

谢谢!

+4

那么你有甚至尝试一些东西,得到了地方停留,还是你只是要求我们的代码为你? – Rizier123

+0

'while($ i <5)'...然后在'while'中增加'$ i',否? http://php.net/manual/en/control-structures.while.php – chris85

+0

确实这是一个很好的策略,实际上_learn_东西?通过询问问题的答案? – arkascha

回答

-1

要用while循环替换for循环,可以在启动while循环之前声明变量,这将指示循环的当前迭代。然后你可以在while循环的每次迭代中递减/递增这个变量。所以,你会是这样的:

$counter = 0; 
while ($counter < 5) { 
    echo ""; 
    echo "<td>" . $ab . "</td><td>" . $xy . "</td>"; 
    $ab += $xy;  
    $xy += $ab;  
    echo "</tr>"; 
    $counter++; 
} 
一般

for ($i = 0; $i < x; $i++) { 
    do stuff 
} 

等同于:

$counter = 0; 
while ($counter < x){ 
    do stuff 
    counter++; 
} 
0
$ab = 0; 
$xy = 1; 
echo "<table>"; 
$i = 0; 
while ($i < 5) { 
    echo "<tr><td>$ab</td><td>$xy</td></tr>"; 
    $ab += $xy; 
    $xy += $ab; 
    $i++; 
} 
echo "</table>"; 

对于解释:
相较于 “为”循环,你必须在打开循环之前初始化“计数器”[$ i = 0]
在循环中,您所指定的条件继续循环[$ I < 5]
而且某处进入死循环,你增加你的“反击” [$ I ++]
你的“计数器”,可以增加或减少,或直接设置;这完全是关于你的代码逻辑和你的需求。

while ($i < 5) { 
    echo "<tr><td>$ab</td><td>$xy</td></tr>"; 
    $ab += $xy; 
    $xy += $ab; 
    if ($ab == 22) { // If $ab is equal to a specific value 
     /* Do more stuff here if you want to */ 
     break; // stop the loop here 
    } 
    $i++; 
} 

这个例子也与“for”循环工作:

你也可以随时在你所需要,看一个例子情况下,要打破循环。
而且还有另一个关键字,“继续”,用来告诉“跳”到下一个循环迭代:

while ($i < 5) { 
    $i++; // Don't forget to increase "counter" first, to avoid infinite loop 
    if ($ab == 22) { // If $ab is equal to a specific value 
     /* Do more stuff here if you want to */ 
     continue; // ignore this iteration 
    } 

    /* The following will be ignored if $ab is equal to 22 */ 
    echo "<tr><td>$ab</td><td>$xy</td></tr>"; 
    $ab += $xy; 
    $xy += $ab; 
} 
+0

尽管此代码片段可能会解决问题,但[包括解释](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要使用解释性注释来挤占代码,因为这会降低代码和解释的可读性! – FrankerZ

+0

你说得对,我做了一些修改 – Marc