Do While Loop
What Is a do...while Loop? In simple terms: A do...while loop runs its code first and checks the condition afterwards . Because of this, the code always runs at least once. Technically: do...while exe
What Is a do...while Loop?
In simple terms: A do...while loop runs its code first and checks the condition afterwards. Because of this, the code always runs at least once.
Technically: do...while executes the body, then evaluates the condition. If the condition is true, the body runs again; if it is false, the loop ends. It is the only PHP loop whose condition is checked after each iteration.
Why It Exists
Some tasks must happen at least once before you can decide whether to repeat them:
- Fetch the first page of results, then continue while more pages exist.
- Generate a code, then generate again while it is already taken.
- Show a menu, then show it again while the user has not chosen "exit".
With a while loop, such code needs the first step duplicated before the loop, or an artificial starting value. do...while expresses "do it, then check" directly.
Syntax
do {
// code that runs at least once
} while (condition);
Note: The semicolon after
while (condition)is required. Leaving it out is a parse error.
Flow
┌──────────────┐
│ loop body │◄──────┐
└──────┬───────┘ │
▼ │
┌──────────────┐ true │
│ condition ? │───────┘
└──────┬───────┘
false
▼
continue after the loop
Example
<?php
$count = 1;
do {
echo "Iteration $count\n";
$count++;
} while ($count <= 3);
Output
Iteration 1
Iteration 2
Iteration 3
while vs do...while
The difference appears only when the condition is false from the start:
<?php
$n = 10;
echo "while:\n";
while ($n < 5) {
echo " body ran with n = $n\n";
}
echo "do...while:\n";
do {
echo " body ran with n = $n\n";
} while ($n < 5);
Output
while:
do...while:
body ran with n = 10
while | do...while | |
|---|---|---|
| Condition checked | Before each iteration | After each iteration |
| Minimum number of runs | 0 | 1 |
| Semicolon after condition | No | Yes |
Choose do...while only when running the body once is correct even if the condition would be false. Otherwise, use while.
Practical Example: Fetching Paginated Results
Many APIs return data in pages and indicate whether more pages exist. You must fetch at least one page to find out:
<?php
// Simulated API: each page returns items and a "has_more" flag
function fetchPage(int $page): array
{
$pages = [
1 => ['items' => ['Keyboard', 'Mouse'], 'has_more' => true],
2 => ['items' => ['Monitor', 'Webcam'], 'has_more' => true],
3 => ['items' => ['Headset'], 'has_more' => false],
];
return $pages[$page] ?? ['items' => [], 'has_more' => false];
}
$page = 1;
$allItems = [];
do {
$response = fetchPage($page);
echo "Page $page: " . implode(', ', $response['items']) . "\n";
$allItems = [...$allItems, ...$response['items']];
$page++;
} while ($response['has_more']);
echo "Total items: " . count($allItems) . "\n";
Output
Page 1: Keyboard, Mouse
Page 2: Monitor, Webcam
Page 3: Headset
Total items: 5
Step-by-Step Explanation
- The body fetches the current page — this must happen before we know whether more pages exist.
- Items are added to
$allItemswith the spread operator (see Array Spread Operator). $pageis increased for the next request.- The condition checks the
has_moreflag from the response just received. After page 3, it isfalse, and the loop ends.
With a while loop, you would have to fetch the first page before the loop and at the end of the body, duplicating the request code.
Tip: In production, also add a maximum page count to the condition (for example,
&& $page <= 100) so that a misbehaving API cannot keep the loop running forever.
Practical Example: Generating a Unique Code
<?php
function generateUniqueCode(array $existingCodes, int $length = 6): string
{
$alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$maxAttempts = 10;
$attempts = 0;
do {
$code = '';
for ($i = 0; $i < $length; $i++) {
$code .= $alphabet[random_int(0, strlen($alphabet) - 1)];
}
$attempts++;
} while (in_array($code, $existingCodes, true) && $attempts < $maxAttempts);
if (in_array($code, $existingCodes, true)) {
throw new RuntimeException('Could not generate a unique code.');
}
return $code;
}
$existing = ['K7MQ2X', 'P3RT9A'];
$newCode = generateUniqueCode($existing);
echo "New code: $newCode\n";
var_dump(in_array($newCode, $existing, true));
Output (the code differs on every run)
New code: H8ZQ4M
bool(false)
How It Works
- A candidate code is always generated at least once — the natural use case for
do...while. - The loop repeats only while the code already exists and the attempt limit is not reached.
- After the loop, one final check throws an exception if every attempt collided (extremely unlikely, but handled).
random_int()makes the codes unpredictable (see PHP Random Numbers).
In a real application, the uniqueness check would query the database, and a unique index on the column would provide the final guarantee against duplicates created at the same moment by two requests.
Practical Example: A Simple Menu Loop
Command-line menus show options, read a choice, and repeat until the user exits. Here, the user's choices are simulated with an array:
<?php
$simulatedInput = ['1', '3', '2', '0'];
do {
$choice = array_shift($simulatedInput) ?? '0';
$message = match ($choice) {
'1' => 'Showing your orders',
'2' => 'Showing your profile',
'0' => 'Goodbye!',
default => "Invalid option: $choice",
};
echo "> $choice: $message\n";
} while ($choice !== '0');
Output
> 1: Showing your orders
> 3: Invalid option: 3
> 2: Showing your profile
> 0: Goodbye!
The menu must be shown before the user can choose to exit, so do...while fits naturally. In a real CLI script, $choice would come from readline('Choose an option: ').
Common Mistakes
Missing Semicolon
do {
$i++;
} while ($i < 5) // parse error: missing ;
Fix: End the statement with ;.
Using do...while When Zero Iterations Are Possible
Effect: The body runs once with invalid data — for example, processing the first element of an empty list.
Fix: Use while (or foreach) when the body may need to run zero times.
Forgetting to Change the Condition
Effect: Infinite loop.
Fix: Ensure the body updates something the condition depends on, and add a maximum iteration limit for external data.
Variables Used in the Condition but Defined Inside the Body
This is fine in PHP, because variables created in the body are still available in the condition (PHP has no block scope). But the variable must be assigned in every iteration; otherwise the condition uses a stale value.
Best Practices
- Use
do...whileonly when the body must run at least once. - Remember the semicolon after the condition.
- Add a safety limit (maximum attempts or pages) when the condition depends on external systems.
- Keep the body focused; move complex logic into functions.
Official reference: https://www.php.net/manual/en/control-structures.do.while.php