Skip to content

PHP Tutorial Loops

PHP do…while Loop

Lesson 93 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

A do...while loop is like while, but it checks the condition after the block. So the block always runs at least once.

index.php
PHP
<?php
$number = 10;

do {
    echo "Number is $number\n";
    $number++;
} while ($number <= 3);
Output
OUTPUT
Number is 10

The condition 10 <= 3 is false, but the block already ran once.

Compare it with while, which would print nothing here.

Notice the semicolon

A do...while ends with a semicolon after the condition. Forgetting it is a syntax error.

When to use it

Use do...while when the work must happen once before you can decide whether to repeat. Typical examples are “ask, then check the answer”, “try, then check if it worked” and menus.

index.php
PHP
<?php
$attempts = 0;

do {
    $attempts++;
    $success = $attempts >= 3; // pretend the third try works
    echo "Attempt $attempts: " . ($success ? "ok" : "failed") . "\n";
} while (!$success && $attempts < 5);
Output
OUTPUT
Attempt 1: failed
Attempt 2: failed
Attempt 3: ok

Generate a unique code

index.php
PHP
<?php
$taken = ["A1", "A2"];
$candidates = ["A1", "A2", "A3"];
$i = 0;

do {
    $code = $candidates[$i++];
} while (in_array($code, $taken, true));

echo "Free code: $code";
Output
OUTPUT
Free code: A3
info
do…while is rare
Most loops in real code are for or foreach. Keep do...while for the cases where “run first, check later” is exactly what you mean.