• Home
  • PHP do while Loop

PHP do while Loop

The do...while loop is a type of looping statement in PHP that allows you to execute a block of code multiple times as long as a condition is true. It is similar to the while loop, but the condition is checked at the end of each iteration instead of at the beginning.

The syntax for a do...while loop in PHP is as follows:

do {
// code to be executed
} while (condition);

The code inside the curly braces is executed, and then the condition is checked. If the condition is true, the loop continues and the code is executed again. If the condition is false, the loop ends and control is passed to the next statement after the loop.

Here is an example of a simple do...while loop that counts from 1 to 10:

$i = 1;
do {
echo $i . "\n";
$i++;
} while ($i <= 10);

This loop will output the numbers 1 through 10, each on a new line. The variable $i is incremented by 1 at the end of each iteration, so that the loop eventually ends when $i becomes greater than 10.

One key difference between the do...while loop and the while loop is that the code inside the do...while loop is always executed at least once, even if the condition is false to begin with. This is because the condition is checked at the end of the loop, after the code has been executed.

Here is an example of a do...while loop that will only execute once, even though the condition is false:

$i = 1;
do {
echo $i . "\n";
$i++;
} while ($i > 10);

In this case, the code inside the loop will be executed once, and then the condition will be checked. Since $i is not greater than 10, the loop will end and the code after the loop will be executed.

You can also use the break statement to exit a do...while loop early, or the continue statement to skip the rest of the current iteration and move on to the next one.

It is important to use looping statements carefully, as it is easy to create infinite loops if the condition is always true or if you forget to increment the loop variable. Infinite loops can cause your program to hang or crash, so it is important to make sure that the condition will eventually become false at some point.