Loops are part of the programming structure of any language. We use the logic in different conditions and within our scripts. Now that we’ve discussed the while loop, we’ll discuss the do while loop a bit different from the while loop.

The difference between a while loop and a do while loop
In a while loop, the condition is checked at the beginning of the loop and, if true, the code in the loop is executed. This process is repeated until the condition becomes false. In the case of a do while loop, the condition check is done at the end of the loop. Therefore, even if the condition is false, the script in the loop is executed at least once. This is the basic difference between a do while loop and a while loop.

Let’s start with a simple script that uses a do while loop to understand the syntax. The condition here is checked at the end of the loop, so the code inside the loop is executed once.

$i=1;

do{

echo $i;

echo "<br>";

} while ($i > 1);

We can see in the above code that even if the $ i value is 1, this is not the correct condition for the loop setting. The script will still print $ i once the condition is checked at the end of the loop. To compare these two types of loops, check this code.

<?Php

$i=1;

do{

echo $i; // Out put will be there

echo "<br>";

} while ($i > 1);

echo "<hr>";

$i=1; // we assigned a value to the variable again here

while($i > 1){

echo $i; // No output as loop will not be executed

echo "<br>";

}

?>

Use the break statement to stop execution of the do while loop
Like other loops, we can use the break statement to exit the loop. In the following code, we try to display numbers from 5 to 15, but once the $ i value reaches 11, the if condition becomes true and the break statement is executed. So the cycle stopped there, the program execution. Here is the code.

$i=5;

do{

echo $i;

echo "<br>";

$i=$i+1;

if($i>10){break;}

} while ($i < 15);