Beginner Fundamentals

PHP While Loops

Loops let you run the same block of code many times. The while loop repeats as long as a condition stays true.

The while loop

The condition is checked before each run.

<?php
$i = 1;
while ($i <= 5) {
    echo $i . " ";
    $i++;
}
// Output: 1 2 3 4 5

Always update the variable inside the loop, or it will run forever.

The do…while loop

This loop runs the body once before checking the condition, so it always executes at least once.

<?php
$i = 10;
do {
    echo "Runs once: $i";
} while ($i < 5);

Break

break exits the loop immediately.

<?php
$i = 1;
while (true) {
    if ($i > 3) {
        break;
    }
    echo $i . " ";
    $i++;
}
// Output: 1 2 3

Continue

continue skips the rest of the current iteration and moves to the next.

<?php
$i = 0;
while ($i < 5) {
    $i++;
    if ($i == 3) {
        continue; // skip 3
    }
    echo $i . " ";
}
// Output: 1 2 4 5