
PHP Do While Loop
In PHP, the “do-while” loop is a type of loop that executes a block of code repeatedly as long as a specified condition is true. The key difference between the “do-while” loop and the regular “while” loop is that the “do-while” loop executes the code block at least once before checking the loop condition.
The syntax of the “do-while” loop is as follows:
do {
// Code to be executed
} while (condition);
Here’s an example of how the “do-while” loop works:
$counter = 1;
do {
echo "Number: " . $counter . "<br>";
$counter++;
} while ($counter <= 5);
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
In the example above, the “do-while” loop will run at least once because the code block is executed before checking the loop condition. The loop will continue as long as the value of $counter
is less than or equal to 5. After each iteration, the value of $counter
is incremented by 1.
The “do-while” loop is useful when you want to ensure that a specific code block is executed at least once, regardless of whether the loop condition is initially true or false. It is particularly helpful when you need to prompt for user input at least once and then continue the loop based on the user’s input.