while and do...while Loops

Repeat a block of code as long as a condition remains true.

Syntaxwhile (condition) { // code }

A while loop runs its block as long as the condition is true, checking before each iteration.

A do...while loop runs the block at least once, then keeps going while the condition is true.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Read lines from a file handle until feof() returns true using a while loop.
  • Poll a job queue database table with do...while until the queue is empty or a timeout is reached.
  • Keep prompting a CLI user for valid input inside a do...while until they enter a number in range.

More examples

Basic while loop

The condition is checked before each iteration; when it becomes false the loop exits.

Example · php
<?php
$count = 1;

while ($count <= 5) {
    echo "Iteration $count\n";
    $count++;
}

while reading from an array

array_shift() removes and returns the first element; checking empty() makes the loop self-terminating.

Example · php
<?php
$queue = ['job1', 'job2', 'job3'];

while (!empty($queue)) {
    $job = array_shift($queue);
    echo "Processing: $job\n";
}

do...while runs at least once

do...while always executes the body first, then checks the condition — ideal for retry loops.

Example · php
<?php
$attempts = 0;
$success  = false;

do {
    $attempts++;
    // Simulate a task that may fail
    $success = (random_int(1, 3) === 1);
} while (!$success && $attempts < 5);

echo "Succeeded after $attempts attempt(s)";

Discussion

  • Be the first to comment on this lesson.