The do…while loop will always execute the block of code at least once, then check the condition and continue repeating the loop as long as the specified condition remains true.
Output $i as long as $i is below 6:
$i do |
Note: In a do…while loop, the condition is assessed AFTER the statements inside the loop are executed. This ensures that the do…while loop will run its statements at least once, even if the condition is false. See the example below. |
Let’s observe what happens if we set the $i variable to 8 instead of 1 before running the same do…while loop again:
Set $i to 8, then output $i as long as $i is less than 6:
$i do |
The code will execute once, even if the condition is never true.
The break statement allows us to exit the loop, even if the condition remains true.
Terminate the loop when $i reaches 3:
$i do |
The continue statement allows us to skip the current iteration and proceed to the next one.
Skip to the next iteration if $i is 3:
$i do |