While and Do-While Loops
Tutorials

The while and do-while loops are control structures used to repeat a block of code for as long as a specific condition remains true. T

hese are ideal when you do not know exactly how many loops (iterations) your code will need to make before it starts, and you instead want to rely entirely on a changing condition to stop it.

The while Loop

A while loop checks its condition before executing the code inside the curly braces.

If the condition evaluates to false on the very first check, the code inside the loop will never run.

<?php
while (condition) {
    // Code to repeat
}

Implementation Example

<?php
$count = 1;

while ($count <= 3) {
    echo "The count is: " . $count;
    $count++; // Incrementing ensures the condition eventually becomes false
}

How the Logic Flows:

The Check: PHP looks at the condition ($count <= 3). Since 1 <= 3 is true, it enters the loop.

The Execution: It prints the text and increments $count to 2.

The Repeat: It returns to the top and checks again (2 <= 3). This continues until $count is incremented to 4.

The Exit: On the next check, 4 <= 3 evaluates to false. PHP completely skips the block and moves to the code below it.

The do-while Loop

Unlike the standard while loop, a do-while loop checks its condition after executing the code block.

This guarantees that the code inside the curly braces will always run at least once, regardless of whether the condition is true or false from the start.

<?php
do {
    // Code to repeat (runs at least once)
} while (condition);

Tip for beginners: Remember to place a semicolon ; at the very end of the closing while statement.

<?php
$count = 10;

do {
    echo "This will print exactly once, even though 10 is not less than 5!";
    $count++;
} while ($count < 5);

How the Logic Flows:

The Execution: PHP enters the do block immediately without checking any rules. It prints the text and increments $count to 11.

The Check: PHP reaches the bottom and evaluates the condition (11 < 5).

The Exit: Because the condition is false, PHP terminates the loop right there and moves forward. Even though the condition was never true, your code successfully ran once.

To Top