Technology Programming

How to prevent an endless PHP loop from breaking your program

Loops in PHP let a process continue to happen over and over again until a certain condition is met. If this condition is never met, the program will continue to cycle though the same bit of code for all eternity, leaving you with a blank white page scratching your head as to what went wrong. It is important to make sure it is actually possible to satisfy your exit loop condition.

While Loops
<?php $num = 1;
while ( $num $num++;
} ?>


In the example above, we need to make sure that we have the $num++ in our code. If we don't increase our number each loop it will never finish!

For Loops
<?php
for ($num=1; $num $num++ )
{
print $num . " ";
}
?>


Again in this example using a for loop, we need to make sure that we use $num++ so that we are actually changing the number, and the loop has a chance to meet it's condition and end.

ForEach Loops
Since a ForEach loop uses data from an array, than the condition for ending the loop is met when all of the data in the array has been used. For this reason you don't have to worry about it being recursive, as long as you don't accidently redefine the array on every line!

Leave a reply