PHP While Loop Example

Loop while a condition is true with while and do-while. Edit the code below and press Run to execute it with real PHP in your browser.

Code Editor
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

How this while loop example works

A while loop checks its condition before every iteration, so the body may run zero times. Make sure something inside the loop changes the condition (here $counter++); otherwise the loop never ends. The online compiler stops scripts that run longer than 10 seconds.

do-while runs at least once

<?php
$n = 10;
do {
    echo "Runs once even though n = $n\n";
} while ($n < 5);

Output:

Runs once even though n = 10