【问题标题】:PHP for loop to while loopPHP for 循环到 while 循环
【发布时间】:2016-08-14 17:49:14
【问题描述】:

嘿学习考试,并有这个循环。

<?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 循环?需要注意什么,

谢谢!

【问题讨论】:

  • 那么您是否尝试过某些东西并卡在某个地方,或者您只是要求我们为您编写代码?
  • while ($i &lt; 5) ... 然后在while 中增加$i,不是吗? php.net/manual/en/control-structures.while.php
  • 确定这是一个真正学习的好策略吗?通过询问问题的答案?
  • @arkascha 我问要记住什么......我确实通过查看代码是如何学习的,然后我可以弄清楚它是如何工作的。没说我很好什么的
  • 抱歉,但这不是学习编码的方式。如果您改为采用循环结构的定义(参见带有示例的官方文档)并自己解决问题,您将更加成功。完成后,您可以说您了解如何使用这些语言结构。

标签: php


【解决方案1】:
$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>";

解释:
与“for”循环相比,您必须在打开循环之前初始化“计数器” [ $i = 0 ]
在循环内部,您指定继续循环的条件 [ $i 在循环的某个地方,你增加了你的“计数器”[$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;
}

【讨论】:

  • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性 cmets 挤满你的代码,因为这会降低代码和解释的可读性!
【解决方案2】:

要将for 循环替换为while 循环,您可以在启动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++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2012-10-02
    • 2021-03-27
    • 2012-09-19
    • 1970-01-01
    • 2014-08-21
    • 2018-11-05
    相关资源
    最近更新 更多