Skip to main content

The PHP while Loop

A while loop keeps repeating its code for as long as its condition remains true.

Tip: PHP tests the condition before every pass, including the first. A condition that is false from the start means the code inside never runs at all.

Print numbers with while

$i starts at 1 and is printed and increased on each pass, until it is no longer below 6:

Prompt
Write a PHP script that sets a variable $i to 1. Use a while loop to print $i as long as $i is less than 6. Increment $i by 1 in each iteration.
Output: PHP script

While loop syntax

In its general form, a while loop looks like this:

index.php
while (condition) {
  // code to be executed repeatedly as long as condition is true
}

The PHP break Statement

A break ends the loop on the spot, even when the condition would allow it to keep going.

Stop the loop with break

The loop ends when $i equals 3, leaving just 1 and 2 in the output:

Prompt
Write a PHP script that sets $i to 1. Use a while loop with a condition of $i < 6. Inside the loop, if $i equals 3, use break to stop the loop. Otherwise, echo $i and increment $i.
Output: PHP script

The PHP continue Statement

The continue statement drops the rest of the current pass, and the loop moves on to the following one.

Skip iteration with continue

Because $i is increased before the check, the loop keeps moving, and only the number 3 is left out of the output:

Prompt
Write a PHP script that sets $i to 0. Use a while loop with a condition of $i < 6. Increment $i at the start of each iteration. If $i equals 3, use continue to skip the echo. Otherwise, echo $i.
Output: PHP script

Alternative Syntax

A while loop can also be written without braces: put a colon after the condition and finish with endwhile.

While loop with endwhile

This version has the same effect as the first example, printing $i while it is below 6:

Prompt
Write a PHP script that sets $i to 1. Use the alternative while loop syntax with endwhile to print $i as long as $i is less than 6. Increment $i in each iteration.
Output: PHP script

Step 10

A loop counter can grow by any amount. To reach 100 in steps of ten, add 10 to the counter on each pass instead of 1.

Count to 100 by tens

The counter is raised before it is printed, so the output runs from 10 to 100:

Prompt
Write a PHP script that sets $i to 0. Use a while loop with a condition of $i < 100. Inside the loop, increment $i by 10, then echo $i followed by a line break.
Output: PHP script