Do While Loop

JA JASWANT Updated 17 Oct 2026
5 min read ·Lesson 7 of 248
In this post

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
whiledo...while
Condition checkedBefore each iterationAfter each iteration
Minimum number of runs01
Semicolon after conditionNoYes

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

  1. The body fetches the current page — this must happen before we know whether more pages exist.
  2. Items are added to $allItems with the spread operator (see Array Spread Operator).
  3. $page is increased for the next request.
  4. The condition checks the has_more flag from the response just received. After page 3, it is false, 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

  1. A candidate code is always generated at least once — the natural use case for do...while.
  2. The loop repeats only while the code already exists and the attempt limit is not reached.
  3. After the loop, one final check throws an exception if every attempt collided (extremely unlikely, but handled).
  4. 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...while only 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

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

Ask questions about Do While Loop and get answers drawn from it.

Signed-in readers only.