The do while loop executes a block of code once and then runs the loop as long as the given condition is true.
PHP do while loop executes the code at least once always because the condition is checked after end of loop. The main difference between while and do while loops is that while loop checks the condition at the beginning and where as do while loop checks the condition at the end of the loop.
Syntax
do {
// code to be executed;
} while (check condition is true);
PHP Example 1:
<?php
$num=1;
do{
echo "The value is $num <br/>";
$num++; //increment value by 1
}while($num<=5); // checks condition true or false
?>
Output:
The value is 1
The value is 2
The value is 3
The value is 4
The value is 5
PHP Example 2:
Look at below code. PHP executes do while loop at one time and gives output 'The value is 6 ' and then it checks while condition at end of loop.
<?php
$num=6;
do{
echo "The value is $num <br/>";
$num++;
}while($num<=5);
?>
Output:
The value is 6
Difference between while and do-while loop
- The while loop is also called as entry control loop when The do while loop is also called as exit control loop.
- The while loop checks condition first, and then block of statements will be executed. The do while loop runs block of statements first and then condition will be checked.
- The body of the loop does not execute if the condition is false in while loop. The body of the loop executes at least once, even if the condition is false in do while loop.
- while loop does not use a semicolon to terminate the loop when Do while loop uses semicolon to terminate the loop at ends .
Comments