Learn how the do...while loop works in PHP. Discover its syntax, how it differs from while, and view practical examples to master this loop construct.
do-while Loop in PHPA do-while loop is very similar to a while loop, but with one key difference: the condition is checked after the loop’s code has been executed. This means the loop always runs at least once, regardless of whether the condition is true or false at the start.
do-while and while Loopswhile Loop: Checks the condition before executing the loop. If the condition is false initially, the loop will never run.do-while Loop: Executes the loop once, then checks the condition. If the condition is false after the first iteration, the loop stops.do-while Loopdo {
// Code to execute
} while (condition);
do-while Loop<?php
$i = 0;
do {
echo $i; // This will print 0
} while ($i > 0); // The condition is false, so the loop stops after one iteration
?>
Explanation:
$i is initially 0.$i > 0 is checked.$i > 0 is false, the loop stops after the first iteration.do-while<!DOCTYPE html>
<html lang="en">
<head>
<title>PHP - Do While Loop Example</title>
</head>
<body>
<?php
$x = 6; // Set initial value of $x
do {
echo "The number is: $x <br>"; // Prints $x
$x++; // Increments $x
} while ($x <= 5); // Loop stops because $x is no longer <= 5
?>
</body>
</html>
Output:
The number is: 6
Explanation:
$x = 6, printing “The number is: 6”.$x <= 5 is checked after the first iteration, and since it’s false, the loop stops.do-while loop always runs at least once, regardless of the condition.while loop where the condition is checked first.