The Do-While Loop
The do-while
loop is a loop with a postcondition that first executes the block of code and then checks the condition. If the condition is true, the loop repeats. The main difference from while
is that the loop body will be executed at least once.
Syntax
do {
// loop body
} while (condition);
Example
A simple example of outputting numbers from 1
to 5
:
<?php
$i = 1;
do {
echo $i . ' ';
$i++;
} while ($i <= 5);
?>
Code execution result:
1 2 3 4 5
Example
The loop will execute at least once, even if the condition is false:
<?php
$flag = false;
do {
echo 'This will be printed once';
} while ($flag);
?>
Code execution result:
'This will be printed once'
Example
Processing an array using a do-while
loop:
<?php
$arr = [1, 2, 3];
$i = 0;
do {
echo $arr[$i] . ' ';
$i++;
} while ($i < count($arr));
?>
Code execution result:
1 2 3