I have this loop
while (count($arr) < 7)
{
$string = 'xx';
for ($i=0; strlen($string) < 4; $i++)
{
$string = $string.'1';
}
echo "<br>array length is less than 7, word $string is created.";
$arr[] = $string;
}
Every time I run this part of the code, my xampp local server would time out and gives the server not found error.
I have found that if I delete the inner for
loop, it would run fine. Is there anything wrong with putting the for
loop inside the while
loop?
Also, my conditional statement strlen($string) < 4
in the for
loop does not have any reference to the $i
variable, but I don't see any thing not logical of having a conditional statement not related to the counter. Am I wrong, does it require some sort of comparison against the counter?
TIA
Nothing wrong with having a for inside a while.
Your "for" would be better a bit clearer as
while(strlen($string) < 4) {
$string = $string.'1';
}
I don't see any issues whatsoever with your php.
I copied your code exactly and there was no infinite loop at all.
The result I got was as follows:
<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.
<br>array length is less than 7, word xx11 is created.
My only suggestion would be to change:
$string = $string.'1';
to
$string .= '1';
来源:https://stackoverflow.com/questions/9676726/php-for-loop-inside-a-while-loop-correct-syntax