HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Do While Loop

The do...while loop is a variation of the while loop. The key difference is that it checks the condition after executing the code block. This means the loop will always execute the block of code at least once.


The do...while Syntax

The code is executed first, and only then is the condition tested. If the condition is true, the loop repeats.

<?php
    $x = 1;

    do {
        echo "The number is: $x <br>";
        $x++;
    } while ($x <= 5);
?>

Executing Once Regardless

Even if the condition is false from the start, the do block will run exactly once. This is what separates it from a standard while loop.

<?php
    $x = 6;

    do {
        echo "The number is: $x <br>";
        $x++;
    } while ($x <= 5);

    // Outputs: The number is: 6
?>
Logic Note: In cases where you want a user to see a menu at least once before they decide to quit, the do...while loop is the ideal choice.

while vs. do...while

Loop Type Condition Check Minimum Iterations
while Pre-condition (at the top) 0
do...while Post-condition (at the bottom) 1
Pro Tip: Don't forget the semicolon (;) after the while ($condition) part in a do-while loop. It is required for the code to compile correctly.

Key Points to Remember

  • The do...while loop executes the code block once before checking the condition.
  • It will continue to loop as long as the condition is TRUE.
  • The loop is guaranteed to run at least once.
  • Always include an increment/update statement to avoid infinite loops.
  • A semicolon is mandatory at the end of the while line in this syntax.