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
doblock will always execute once before checking thewhilecondition. - After the block has executed, the condition is evaluated. If it is
true, the code block will execute again. Iffalse, the loop ends.
Example
<?php
$i = 0;
do {
echo "The value of i is: $i<br>";
$i++;
} while ($i < 5);
?>
do...while with a Condition that is Initially False
$istarts at 5, so thewhilecondition($i < 5)isfalse.- Despite this, the code inside the
doblock 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);
?>