Do while loops

PHP do-while loops are almost the exact same as PHP while loops. The difference between the two is when the expression is checked. In a while loop the expression is checked at the start of each loop or iteration whilst in a do-while loop the expression is checked at the end of each loop/iteration. As a result of the behaviour of the do-while loop the code in the loop is guaranteed to run at least once.

The syntax

The syntax of a do-while loop takes the following form:

<?php
do {
   
// loop code
} while(expression);
?>

As mentioned above the loop code will be executed and then expression when evaluated. If the expression is true the loop will run the code again else it PHP will continue to process the code after the loop.

A simple example

The below code outputs the numbers 1-5:

<?php
$i 
1;
do {
    echo 
$i;
    
$i++;
} while(
$i <= 5);
?>

You're unlikely to ever use a do-while loop in PHP as most of the time it can be same result can be achieved with another type of loop.