简体   繁体   English

PHP 中的 For 循环之谜

[英]For-loop mystery in PHP

Using PHP 5.6, why does this code outputs使用PHP 5.6,为什么这段代码输出

2
5
8
11

instead of代替

3
6
9

? ?

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

Because i starts at 0, not 1. Lets see what is happening:因为我从 0 开始,而不是 1。让我们看看发生了什么:

Loop 1循环 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循环 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.所以你加2,回显然后加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.您可能希望 for 循环中的i++在代码之前运行,但它在代码末尾运行。 From the PHP website :PHP 网站

At the end of each iteration, expr3 is evaluated (executed).在每次迭代结束时, expr3被评估(执行)。

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.如果您希望输出为 3、6、9,那么您需要在循环开始时将 i 初始化为 1。

for($i = 1; $i < 10; $i++)

The increment ( i++ ) in the loop header happens after the loop body is executed.循环头中的增量 ( i++ ) 发生循环体执行之后。 So, i is initialized to 0, then you add 2 and print it.所以, i被初始化为 0,然后你添加 2 并打印它。 Then, the loop header increments it to 3, then you add 2 and print it again...然后,循环标题将其增加到 3,然后添加 2 并再次打印...

In the first iteration, you add 0 + 2 , because you declared $i to be 0 , so the output would be 2. then with the $i++ you do the same as you would write $i += 1 .在第一次迭代中,您添加0 + 2 ,因为您将 $i 声明为0 ,因此输出将为 2。然后使用$i++执行与写入$i += 1 So now the value of $i is 3.所以现在$i的值是 3。

Then you add again 2 which gives you 5 as an output, then you add another 1. Value of $i = 6, add 2... outputs 8... add 1... add 2... outputs 11...然后你再次添加 2 给你 5 作为输出,然后你再添加 1. $i = 6 的值,添加 2... 输出 8... 添加 1... 添加 2... 输出 11.. .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM