In this tutorial, you will learn how to use Do While loop in PHP to execute a block of code repeatedly with the help of examples.
PHP do while loop executes a block of codes until the condition specified in the while condition is true. This is a variant of the while loop. In the case of the do-while loop, the block of codes executed once first, and then the condition is evaluated. If the condition is true, the loop will repeat the execution of the code again until the specified condition becomes false.
Difference between While and Do-While Loop
The main difference between While and Do-While loop is that the do-while loop checks the condition at the end, whereas the while loop checks the condition at the beginning. Therefore, for the do-while loop, the block of code will execute at least once even if the condition in do-while is false.
PHP do while loop syntax
do{ // Code to be executed } while(condition);
Example
<?php $num=1; do { echo "$num<br/>"; $num++; }while($num<=10); ?>
Output
2
3
4
5
6
7
8
9
10
Example 2
<?php $x = 1; do { echo "Welcome to Tutorialsbook! </br>"; $x++; } while ($x < 1); ?>
Output