For-loop conditions checking PHP

474 views Asked by At

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

3

There are 3 answers

0
n-dru On BEST ANSWER

It is checking it every iteration, for example:

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

will last until memory is exhausted, it will yield for example:

Fatal error: Allowed memory size of 536870912 bytes exhausted

To change it to checking only once once, use this:

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

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 ]

0
Hassaan Salik On

As $i is incremented in every iteration. Condition is also checked in every iteration against new value of $i as long as loop is running.