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:

DO {
[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:

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.