PHP DO WHILE Loop
DO .. WHILE is used in PHP to provide a control condition. The idea is to execute a piece of code while a condition is true. The basic syntax of DO .. WHILE is as follows:
[code to execute]
} WHILE (conditional statement)
The difference between DO .. WHILE and WHILE is that DO .. WHILE will always execute the [code to execute] at least once, and in a WHILE construct, it is possible for the [code to execute] to never execute.
Let's look at an example. Assuming we have the following piece of code:
$i = 5
The output of the above code is:
value is now 5
During the 1st iteration, $i = 5, the print statement is executed, $i gets decreased by 1 and becomes 4, then PHP checks the expression, ($i > 3), which turns out to be true. Therefore, the loop continues.
During the 2nd iteration, $i = 4, the print statement is executed, $i gets decreased by 1 and becomes 3, then PHP checks the expression, ($i > 3), which is no longer true. Therefore, PHP exits the loop.
If we change the above code to:
$i = 0
The output would then be:
value is now 0
Even though the expression ($i > 3) is false from the very beginning, one line is still printed out because in DO .. WHILE, the code in the bracket following DO is always executed at least once.