In this lesson, you will learn about the PHP do while loop, the difference between it and the while loop, and examples to understand the topic better.
In the do-while loop, the code block is run at least once before assessing the condition. The do…while loop continues to run until the condition is false.
do { code to be processed here; } while (condition is true);
Example
<?php echo "PHP ***do-While loop*** Example"; echo "<br>"; echo " ------------do-while loop ------------------ "; echo "<br>"; echo "The table of 2 "; echo "<br>"; $var = 1; do { $evennumber = 2 * $var; echo "2 * $var is $evennumber <br/>"; $var++; } while ($var <= 10) ?>
Output
PHP ***do-While loop*** Example ------------do-while loop ------------------ The table of 2 2 * 1 is 2 2 * 2 is 4 2 * 3 is 6 2 * 4 is 8 2 * 5 is 10 2 * 6 is 12 2 * 7 is 14 2 * 8 is 16 2 * 9 is 18 2 * 10 is 20
The while loop evaluates the condition at the beginning of each iteration; if the condition is false, the loop will exit and never execute the code. Regardless of the condition, the loop will always execute at least once in the do-while loop. The loop will stop running once the condition is evaluated to be false.
This concludes the PHP do while Loop lesson. In the next lesson, you will learn about two essential keywords that we use with loops, the break and continue.