• Home
  • Do-while loop vs while loop PHP?

Do-while loop vs while loop PHP?

In PHP, the do...while loop and the while loop are very similar, as they both allow you to execute a block of code multiple times as long as a condition is true. The main difference between the two is the point at which the condition is checked.

The while loop checks the condition at the beginning of each iteration, before the code inside the loop is executed. If the condition is false, the loop ends and control is passed to the next statement after the loop. If the condition is true, the code inside the loop is executed, and then the condition is checked again at the beginning of the next iteration.

Here is an example of a while loop in PHP:

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

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.

The do...while loop, on the other hand, checks the condition at the end of each iteration, after the code inside the loop has been executed. This means that the code inside the loop will always be executed at least once, even if the condition is false to begin with.

Here is an example of a do...while loop in PHP:

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

This loop will also output the numbers 1 through 10, each on a new line. The main difference is that the code inside the loop will be executed once before the condition is checked, whereas in the while loop the condition is checked before the code inside the loop is executed.

In general, the while loop is preferred over the do...while loop when the condition can be checked before the code inside the loop is executed, as it avoids executing the code unnecessarily if the condition is false to begin with. The do...while loop is useful when you want to ensure that the code inside the loop is executed at least once, regardless of the initial value of the condition.

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