The do...while loop in PHP executes a block of code at least once before checking the condition. This makes it ideal when an operation must run initially regardless of the condition.
// Basic structure of a PHP do...while loop
do {
echo "Code executes at least once";
} while (condition);
// Print numbers from 1 to 5 using do...while
<?php
$count = 1;
do {
echo "Count is: $count<br>";
$count++;
} while ($count <= 5);
?>
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
The loop runs first, then checks the condition. Even if $count started above 5, the loop would still execute once.
Test the loop behavior. If you enter a number greater than 3, notice it still runs once because the condition is checked after the first iteration.
do...while when one execution is mandatorydo_while_loop.php