Do While Loop

Ma Mahalakshmi V Updated 14 Nov 2026
5 min read ·Lesson 56 of 255

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 Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays 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 array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting 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 PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types 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 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 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 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 AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
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.