PHP Loops: while, do-while, and for

In PHP, while checks its condition before the body, and do-while checks after it. for keeps initialization, the condition, and the update together, making it convenient for counters. The examples count from 1 to 9 and show what changes when the condition starts out false.

Repeat while a condition is true

The PHP manual for while describes a loop that tests the condition at the beginning of each iteration. Here $i starts at 1 and increases by one on every pass. Save the code in loops.php and run php loops.php in a terminal. Replace the file contents to run each of the following examples separately.

<?php
$i = 1;

while ($i < 10) {
    echo $i;
    $i++;
}
echo PHP_EOL;

The output is 123456789 on one line. After 9 prints, $i becomes 10 and the next test fails. Start with $i = 10 to see the body run zero times. Only the final newline is printed.

Run the body first with do-while

The PHP manual for do-while describes a loop that executes the body before checking its condition. The semicolon after the closing parenthesis is part of the syntax. Use this form when the first pass computes a result you need to decide whether to repeat.

<?php
$i = 1;

do {
    echo $i;
    $i++;
} while ($i < 10);
echo PHP_EOL;

Starting at 1 gives 123456789. Start at 10 and you get 10 once. The body prints 10 and increments $i to 11 before PHP reaches the first condition check.

Keep initialization, condition, and update together with for

The The PHP manual for for explains the order. PHP runs the first expression once at startup, tests the second before each pass, and evaluates the third after each normal completion of the body. Here the three expressions describe a single counter in one place.

<?php
for ($i = 1; $i < 10; $i++) {
    echo $i;
}
echo PHP_EOL;

This also prints 123456789. Change the condition to $i <= 10 to include 10. With the original condition and a starting value of 10, PHP skips the body.

Print a multiplication table with nested loops

The outer loop selects a table from 1 through 3. For each table, the inner loop starts the multiplier again at 1 and proceeds through 9. Initializing the inner counter only once outside the outer loop can leave the later tables empty.

<?php
for ($row = 1; $row <= 3; $row++) {
    for ($column = 1; $column <= 9; $column++) {
        printf("%d x %d = %d\n", $row, $column, $row * $column);
    }
}

The first line is 1 x 1 = 1, the last is 3 x 9 = 27, and there are 27 lines. To use nested while loops, initialize the inner counter inside the outer body and update each counter in its own loop.

Check termination and use loops in HTML

If a loop runs indefinitely, first check that the value used in its condition changes as intended. Try the exact boundary value and a starting value already at the limit to catch off-by-one behavior or skipped iterations. For more on constructing conditions, see PHP manual’s for entry.

The PHP alternative control structure syntax fits loops interleaved with HTML. A colon replaces the opening brace, and endwhile; or endfor; ends the loop.

<?php $i = 1; ?>
<ul>
<?php while ($i <= 3): ?>
    <li><?= $i++ ?></li>
<?php endwhile; ?>
</ul>
<ul>
<?php for ($j = 1; $j <= 3; $j++): ?>
    <li><?= $j ?></li>
<?php endfor; ?>
</ul>

Running the file prints two HTML lists, each containing 1, 2, and 3. To view them in a browser, run php -S localhost:8000 from the same folder and open http://localhost:8000/loops.php. Press Ctrl+C in the terminal when finished.