For 循环条件检查 PHP

For-loop conditions checking PHP

我正在编写带有 for 循环的 PHP 代码:

for($i=1;$i<=count($ArrayData);$i++){
  //some code that changes the size of $ArrayData
}

程序是每次检查循环条件($i<=count($ArrayData))还是只检查一次?

谢谢

每次。
来自 PHP manual:

for (expr1; expr2; expr3)

...
In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

这也可以通过使用如下代码片段来验证:

<?php
function compare($i)
{
    echo 'called'.PHP_EOL;
    return $i < 5;
}
for($i = 0; compare($i); $i++) {}

应该打印:

called
called
called
called
called
called

(注意第 6 次调用 compare,它 returns FALSE,但仍然打印 called。)

[Demo]

As $i 在每次迭代中递增。只要循环是 运行.

,也会在每次迭代中根据 $i 的新值检查条件

每次迭代都会检查它,例如:

for($i=1;$i<count($ArrayData);$i++){
    $ArrayData[]=1;
}

将持续到内存耗尽,例如:

Fatal error: Allowed memory size of 536870912 bytes exhausted

要将其更改为只检查一次,请使用:

for($i=1,$c =count($ArrayData); $i<=$c;$i++){
    $ArrayData[]=1;
}