Sunday, February 19, 2006

Beware of infinite loops

Loops are a great way to get a repetitve task done in a PHP script. There are several kinds of loops: for-loop, foreach-loops, while-loops and do .. while-loops. The all have one thing in common - a stop condition.

A stop condition is an expression that, when it evaluates to true (or any non-negative number), will stop the loop from executing.

Here's a typical for-loop:

for($c=0; $c<10; $c++) {
# do something here
}

This loop will run ten times while $c goes from 0 to 9. Now what would happen if you wrote a stop condition that was never reached? You guessed it. The loop would run forever. Here's an example:

for($c=0; $c<0; $c++) {
# do something here
}

Here, $c gets bigger with each pass through the loop but the stop condition is that $c must be less than zero. That's never going to happen and the loop never quits. Why? Because $c starts at 0 and gets increased by 1 on each pass through the loop.

What about a while-loop? They look like this:

$c = 0;
while($c < 10) {
# do something
$c++;
}

This loop will stop when $c gets to 10. Now suppose you made this subtle typo:

$c = 0;
while($c < 10) {
# do something
$C++;
}

$c never changes! $C keeps getting bigger but this loop doesn't check for that.  So the loop never stops.

If a script seems to be "stuck" and not doing anything - or just not doing what it should be doing - force it to stop, then look for infinite loops. If you see one you're not sure is messed up, try putting an echo() line in the loop body so it prints something to the screen each time the loop executes. You'll see right away if you've found the problem because your screen will fill up and keep growing.

Happy coding!