我写PHP代码用一个for循环:for循环条件检查PHP
for($i=1;$i<=count($ArrayData);$i++){
//some code that changes the size of $ArrayData
}
方案是否检查每一次循环条件($i<=count($ArrayData))
或只有一次?
谢谢
我写PHP代码用一个for循环:for循环条件检查PHP
for($i=1;$i<=count($ArrayData);$i++){
//some code that changes the size of $ArrayData
}
方案是否检查每一次循环条件($i<=count($ArrayData))
或只有一次?
谢谢
这是检查它的每一个迭代,例如:
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;
}
每一次。
从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
是称为,它返回FALSE
,但仍然打印called
。)
[Demo]
$i
如在每次迭代递增。只要循环正在运行,条件也会在每次迭代中对照新值$i
进行检查。
只要条件满足,它就会循环。所以是的,每次迭代都会检查一次。循环是如何知道何时停止的? – treegarden
我认为你的意思是它计算一次或每次数组的大小;它必须每次检查条件。 – Foon