do while loop in PHP, executes first and then checks the condition. it means, do-while loop executes at least once, if condition is false.
Syntax
initialization;
do{
// Code/set of statements
iteration;
}while(condition);
do While loop has four parts
initialization | Initial value or starting number from where do while loop begins. It is the first statement and should be outside of do-while loop. |
Statements | line of codes which enclosed inside curly braces { }. single statement does not requires curly braces. |
iteration | It is used to continue do-while loop, until condition becomes false, It can be increment or decrement. It should be inside loop body. |
condition | In do-while condition comes last, so, do-while loop executes at least once. it tests condition, if true executes the statements inside loop body. |
Example
With false condition
<?php
$n = 1;
do{
echo $n;
$n++;
} while($n > 10);
?>
Above example with execute at least or only once, because of false condition.
Reason: $n value is not greater than 1.
With true condition
<?php
$n = 1;
do{
echo $n;
$n++;
} while($n <= 10);
?>
Outputs from number 1 to 10, because $n value is less than equals to 10, and exits when $n value will be greater than 10.