The do…while statement will execute a block of code at least once – it then will repeat the loop as long as a condition is true.
Syntax
do {
code to be executed;
}
while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
In the below example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10
<?php
$i = 0;
$num = 0;
do {
$i++;
}
while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
Output: Loop stopped at i = 10
Example Program to display table of given number
<?php
$tab=10;
$i=1;
do
{
$t=$tab*$i;
echo $t." ";
$i++;
}
while ($i<=10);
?>
Output: 10 20 30 40 50 60 70 80 90 100