Advertisement

Google Ad Slot: content-top

PHP do while Loop


The do...while loop in PHP is similar to the while loop but with one key difference: it executes the block of code at least once before evaluating the condition. This is useful when you want the code block to run at least once regardless of whether the condition is initially true or false.


Syntax


do {
    // Code to be executed
} while (condition);


  • The do block will always execute once before checking the while condition.
  • After the block has executed, the condition is evaluated. If it is true, the code block will execute again. If false, the loop ends.
Example
<?php
$i = 0;

do {
echo "The value of i is: $i<br>";
$i++;
} while ($i < 5);
?>
Try it yourself

do...while with a Condition that is Initially False


  • $i starts at 5, so the while condition ($i < 5) is false.
  • Despite this, the code inside the do block runs once before checking the condition, printing "The value of i is: 5".


Example
<?php
$i = 5;
do {
echo "The value of i is: $i<br>";
$i++;
} while ($i < 5);
?>
Try it yourself