I am writing PHP code with a for-loop:
for($i=1;$i<=count($ArrayData);$i++){
//some code that changes the size of $ArrayData
}
Does the program check the loop condition ($i<=count($ArrayData))
every time or only once?
Thanks
I am writing PHP code with a for-loop:
for($i=1;$i<=count($ArrayData);$i++){
//some code that changes the size of $ArrayData
}
Does the program check the loop condition ($i<=count($ArrayData))
every time or only once?
Thanks
Every time.
From the 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.
This can also be verified by using a snippet like:
<?php
function compare($i)
{
echo 'called'.PHP_EOL;
return $i < 5;
}
for($i = 0; compare($i); $i++) {}
which should print:
called
called
called
called
called
called
(Note that the 6th time compare
is called, it returns FALSE
, but still prints called
.)
[ Demo ]
It is checking it every iteration, for example:
will last until memory is exhausted, it will yield for example:
To change it to checking only once once, use this: