Current course:

PHP While Loops

If we wanted to count down from a number, we could just do this:

echo "3" . "<br />";
echo "2" . "<br />";
echo "1" . "<br />";

But what if you wanted to count down from a hundred? A thousand? Instead of manually counting down (or up), we can use a "while loop".

The Code

$i = 10;
while($i > 0) {
      echo $i . "<br />";
      $i--; // this is the same as $i = $i - 1;


Line 1: In the first line, we set a variable, called "i" to 10.
Line 2: This starts the "while loop" - it translates to "while the variable $i is greater than zero, continue repeating the stuff between my open and close brackets".
Line 3: This just echos the value of the variable $i.
Line 4: This lowers the value of $i by one - it's the same as writing $i = $i - 1;
Line 5: This is the "close bracket" - when it hits this, it will go back up to the Line 2 (the "while" line)

Other uses

Usually a while loop isn't used to just count down or up from a number. One example is to repeat through a list of people, run some checks on them (eg check to see if they're over 21), and if they match what you want, write them to the page and increment the variable. This would allow you to keep track of how many people passed the check and were written to the page - which allows you to limit the number.