Difference Between while and do-while in PHP

Understanding the distinction between loop structures is fundamental to writing efficient PHP code. This article provides a clear comparison between the while loop and the do-while loop in PHP, explaining their syntax, key structural differences, and practical use cases to help you choose the right control structure for your scripts.

The Core Difference

The fundamental difference between a while loop and a do-while loop in PHP lies in when the loop’s condition is evaluated.


PHP while Loop

In a while loop, PHP evaluates the expression first. If it evaluates to true, the statements inside the loop are executed. This process repeats until the expression evaluates to false.

Syntax and Example

<?php
$count = 5;

while ($count < 3) {
    echo "This message will not be displayed.";
    $count++;
}
?>

In this example, because $count is initially 5 (which is not less than 3), the condition evaluates to false immediately. The code block inside the loop is skipped entirely.


PHP do-while Loop

In a do-while loop, the code block is executed first, and then the conditional expression is evaluated. If the expression is true, the loop repeats. If it is false, the loop terminates.

Syntax and Example

<?php
$count = 5;

do {
    echo "This message will be displayed exactly once.";
    $count++;
} while ($count < 3);
?>

In this example, even though $count is 5 (making the condition $count < 3 false), PHP executes the do block first. The message prints once, $count increments to 6, and then the condition is checked. Since 6 < 3 is false, the loop terminates.


Quick Comparison Summary

Feature while Loop do-while Loop
Control Type Entry-controlled (pre-test) Exit-controlled (post-test)
Minimum Iterations 0 (may never run) 1 (always runs at least once)
Condition Check Before executing the code block After executing the code block
Syntax Note Does not end with a semicolon after the block Requires a semicolon ; after the while (condition)

When to Use Which?