The do-while
loop in PHP is used to execute a block of code at least once, and then repeatedly execute the block as long as a specified condition evaluates to true. This ensures that the code inside the loop is run at least once, even if the condition is false from the beginning.
PHP Do-While Loop
1. Syntax of Do-While Loop
The basic syntax of a do-while
loop is as follows:
do {
// Code to be executed
} while (condition);
Here, the code inside the do
block is executed once, and then the while
condition is evaluated. If it returns true, the loop continues; if false, the loop ends.
2. Example of Do-While Loop
Let's look at a simple example to demonstrate how the do-while
loop works:
$i = 1;
do {
echo "The number is: $i
";
$i++;
} while ($i <= 5);
In this example, the output will be:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
3. Important Points
- The code inside the
do
block is guaranteed to execute at least once. - The condition is checked after the code block has executed.
- If the condition is false, the loop will terminate and control will move to the next statement after the loop.
4. Using Break and Continue Statements
You can use the break
and continue
statements within a do-while
loop to control the flow of execution:
$i = 0;
do {
$i++;
if ($i == 3) {
continue; // Skip the rest of the loop when $i is 3
}
echo "The number is: $i
";
} while ($i < 5);
This will output:
The number is: 1
The number is: 2
The number is: 4
5. Conclusion
The do-while
loop is a useful control structure in PHP that ensures a block of code runs at least once before checking the condition. It's particularly beneficial in scenarios where you want to validate user input or repeatedly process data until a certain condition is met.