How to use a do...while loop in PHP

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.

Syntax

do{
// code to be executed
}
while(
// condition is met
)

Explanation of syntax

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.

Major feature

  • This loop offers scripts the ability to execute the conditional code block even before the condition is checked.

Code

<?php
$counter = 1;
// scenerio 1
do {
echo "The number is: $counter \n";
$counter+=2;
} while ($counter <= 6);
//scenario 2
echo "**********************\n";
$increase =2;
do {
echo "The number is: $increase \n";
$increase++;
} while ($increase <= 1);
?>

Explanation

  • First, create a counter, as is common with loop; other control structures can be used as well. This counter usually indicates how many times the code block will be executed before the end of the loop. In our loop for scenario 1, the counter was $counter, and in scenario 2, it was the variable $increase.
  • Start the 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.
  • Still in the do block, add control to this counter with an increment value. For the first and second scenario we used $counter+=2 and $increase++ respectively.
  • Now, in the 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.

Free Resources