...

View Full Version : Resolved Infinite loop?



PonchoX
03-21-2010, 02:03 AM
hi.
me newbie php.
the following code works fine:


$count = -3;
while ($count <= 10) {
echo $count . ", ";
$count ++;
}

this code ALSO runs fine:


$count = -3;
while ($count <= 10) {
if ($count == 5) {
echo "FIVE!, ";
} else {
echo $count . ", ";
}
$count ++;
}

So, how come THIS code seems to run in infinite loop? All I did was remove the curly-brace between the last echo and increment, and move it to the end.


$count = -3;
while ($count <= 10) {
if ($count == 5) {
echo "FIVE!, ";
} else {
echo $count . ", ";
$count ++;
}
}

Notice there is no curly brace between echo and increment is first code example.

mlseim
03-21-2010, 02:13 AM
Because if count = 5, it will just keep printing "FIVE" and never increment.

Increment outside of the "if-else" statement ....


$count = -3;
while ($count <= 10) {
if ($count == 5) {
echo "FIVE!, ";
} else {
echo $count . ", ";
}
$count ++;
}

PonchoX
03-21-2010, 02:26 AM
Thanks.
I don' yet know enuf about PHP to fully understand what you said, but it seems if it never increments, that's what puts me into the infinite loop.

Seems I made the increment part of the else statement when it shoulda went with the while-loop, yes?

It never did print 'FIVE!' btw (not even once). It just went to 100%-CPU and I had to kill the server. (WAMP)

"Increment outside of the "if-else" statement" .. seems to be the lesson here.

_Aerospace_Eng_
03-21-2010, 10:00 AM
It should increment eventually that is if you didn't have the space here $count ++;

Remove it.

PonchoX
03-22-2010, 07:23 AM
Ah, good catch. Thanks.

Me newbie, obviously.

Newbie mistake. Won't make that mistake again.

Wonder why it worked with the space.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum