Login | Contact Us | Site Map | Resources

PHP Conditions & Loops

Home > PHP Tutorial > While

While

Repetition is something that we all experience. Every night we go to bed, and every morning we get up. It is an endless cycle that loops back to begin all over again. When programming, it is very common to need to repeat the same task over and over again. You can either do this by hand (spending unnecessary time pounding on your keyboard) or you can use a loop.

PHP "while" loops will run a block of code over and over again as long as a condition is true. PHP "for" loops will run a block of code a specified number of times, which we will learn more about later.

First let's take a look at an example of a while loop, after which we will pick it apart and explain it:

<?php
  $count = 1;
  while ($count<=100) {
    echo $count . "<br>";
    $count++;
  }
?>

What does this code do? It echoes the numbers 1-100 with only one number per line. How do five lines of code produce 100 lines? Loops!

After setting a variable with a value of 1, our example sets up a loop that states "while the count is less than or equal to 100, run the following block of code". The block of code echoes the current value of the variable, then increases that value by 1. The loop performed this action until the value of $count was equal to 101, at which point in time the condition was no longer true and the loop was terminated.

A common mistake when running a loop like this is to forget to increment the value of the variable. This causes an endless loop running the exact same code over and over again, prompting eye-rolling, shaking of the head, and mutterings of "Oh, duh!". Trust me. I've been there. More than once.