Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

do while Loop

The PHP do…while Loop

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.

Example

Output $i as long as $i is below 6:

$i = 1;
do {
 echo $i;
 $i++;
} while ($i < 6);
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:

Example

Set $i to 8, then output $i as long as $i is less than 6:

$i = 8;
do {
 echo $i;
 $i++;
} while ($i < 6);

The code will execute once, even if the condition is never true.

The break Statement

The break statement allows us to exit the loop, even if the condition remains true.

Example

Terminate the loop when $i reaches 3:

$i = 1;
do {
 if ($i == 3) break;
 echo $i;
 $i++;
} while ($i < 6);

The continue Statement

The continue statement allows us to skip the current iteration and proceed to the next one.

Example

Skip to the next iteration if $i is 3:

$i = 0;
do {
 $i++;
 if ($i == 3) continue;
 echo $i;
} while ($i < 6);