I receive a LOT of questions about loops and how/when to use them. Hopefully this will answer a few of the basic questions. I'll add more to this as more questions come in.

Always be careful with loops and the syntax you use with them. Unterminated or long-lasting loops can cause pages to take long periods of time to load and can even crash servers. Normally, if you have a never-ending loop your PHP.ini settings (max_execution_time) will stop the loop before it executes for too long. By default, this value is set at 30 seconds.


When Do We Use It?

Want to count to a certain number from a certain number. This is good for showing a certain number of objects or looping through simple arrays.

For Loop Example

For example, I want to show 10 input boxes for a client I can use the following code:

for ( $boxCount = 0; $boxCount <= 10; $boxCount++ )
     echo 'Something '.$boxCount.': <input type="text" name="boxes[]" id="box-'.$boxCount.'" /><br/>';


Something 0:
Something 1:
Something 2:
Something 3:
Something 4:
Something 5:
Something 6:
Something 7:
Something 8:
Something 9:
Something 10:


When Do We Use It?

When we want to go through a complex array with no standardized KEY.

For Each Loop Example

$myArray = array( 'Test Text', 'Something' => 'Else', 'Another', 3453, 234, 'Hello!');
foreach ( $myArray as $KEY => $VALUE ) {
    echo '<b>'.$KEY.':</b> '.$VALUE.'<br/>';


0: Test Text
Something: Else
1: Another
2: 3453
3: 234
4: Hello!


When Do We Use It?

When we want to loop through until a number has hit a certain point or a variable returns false. Commonly used with mysql queries.

While Loop Examples

$x = 0;
while ( $x != 40 )
echo $x;


$randomNumber = rand(20,50); //Gives us a random number. In our example, lets say we found 34.
$numberFound = false;
$guessNumber = 0;
while ( !$numberFound  )  // While NOT Number Found - While loops must remain TRUE to run.
       if ( $guessNumber == $randomNumber ) $numberFound = true;
      else $guessNumber++;
echo 'The number was: '.$guessNumber;


The number was: 34