A do
while
loop in PHP will execute a code block at least once. In this loop, the conditional execution block is run at least once before checking if the condition is evaluated as true
or false
. It is employed when you wish to execute a code block, even when none of the conditions were met.
do{
// code to be executed
}
while(
// condition is met
)
Inside the do()
block, you will add the code block you wish to be executed. This code block will run first, when the loop is parsed, before the condition in the while()
block is checked.
If, after the check, the condition evaluates to false
, the execution of the loop will end. But, if true
, the code block to be executed will keep being executed, and the condition will be checked at each time. This continues until the condition evaluates to false
. This will eventually bring to an end the loop execution.
<?php$counter = 1;// scenerio 1do {echo "The number is: $counter \n";$counter+=2;} while ($counter <= 6);//scenario 2echo "**********************\n";$increase =2;do {echo "The number is: $increase \n";$increase++;} while ($increase <= 1);?>
$counter
, and in scenario 2, it was the variable $increase
.do
block and place in it the code to be executed during the loop. In our case, we echo
the current value of the counter.do
block, add control to this counter with an increment value. For the first and second scenario we used $counter+=2
and $increase++
respectively.while
block, add the condition to be met in order for the loop to continue. For the first and the second scenarios:
$counter <= 6
and $increase <= 1
are the conditions, respectively.Notice how the conditional code block was executed even though the condition in the
while
block was not met.