dousi1970 2015-11-23 13:42
浏览 12
已采纳

PHP中的For循环之谜

Using PHP 5.6, why does this code outputs

2
5
8
11

instead of

3
6
9

?

for ($i = 0; $i < 10; $i++) {
    echo $i += 2 . "<br />";
}
  • 写回答

3条回答 默认 最新

  • dongqiao9583 2015-11-23 13:48
    关注

    Because i starts at 0, not 1. Lets see what is happening:

    Loop 1

    Initiate i, i = 0;
    Check for loop condition ($i < 10). i is 0 so yes, run the loop.
    Add 2 to i and echo. 0 + 2 = 2, echo 2.
    End of loop, add 1 to i. i is 3.
    

    Loop 2

    Check for loop condition ($i < 10). i is 3 so yes, run the loop.
    Add 2 to i and echo. 3 + 2 = 5, echo 5.
    End of loop, add 1 to i. i is 6.
    

    And so on. So you add 2, echo out then add 1.

    You may be expecting the i++ in the for loop to run before the code, but it runs at the end of the code. From the PHP website:

    At the end of each iteration, expr3 is evaluated (executed).

    If you want your output to be 3, 6, 9 then you would need to initiate i to 1 at the start of your loop.

    for($i = 1; $i < 10; $i++)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。