1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

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 <=10 ) { print $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
for ($num=1; $num <= 10; $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!

  1. About.com
  2. Technology
  3. PHP / MySQL
  4. Learn PHP
  5. Endless Loops in PHP

©2014 About.com. All rights reserved.