douyan8772 2017-01-19 15:34
浏览 55
已采纳

php beginner,我可以为多个循环分配相同的变量

Case 1 loop inside another loop Can I assign both the $i variable for incrementing?

for($i=0; $i < 10; $i++)
{
  for($i=0; $i < 5; $i++)
  {
     echo "You are too cute";
  }
}

Case 2 : if it's not inside, Could I declare $i for both?

like this

for($i=0; $i < 10; $i++)
{

}
for($i=0; $i < 5; $i++)
{

}
  • 写回答

4条回答 默认 最新

  • dongzouya5792 2017-01-19 16:00
    关注

    There are already some answers that are just fine, but here's a slightly different perspective.

    It depends on what you mean by "can". You can do this in the sense that it is syntactically correct PHP code.

    for($i=0; $i < 10; $i++)
    {
      for($i=0; $i < 5; $i++)
      {
         echo "You will never see this text in your browser.";
      }
    }
    

    But because a loop does not introduce a new variable scope in PHP, it creates an infinite loop.

    The outer loop will execute once, then the inner loop will reset $i to 0, increment it to 5, return control to the outer loop, which will execute once, immediately causing the inner loop to start again, resetting $i to 0 and incrementing it to 5, and so on, forever (at least until your script times out). The outer loop can never end because the inner loop affects $i so that it can never satisfy the exit condition of the outer loop.

    In other words, just use a different variable for the inner loop. Removing one integer variable is not going to be a noticeable optimization of your code, if that's what you're concerned about.

    In the second example, there's no reason not to reuse $i.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大