Originally published on zero2php.dev — part of the Zero to PHP course. View this lesson on the original site.

while

while checks the condition before each iteration:

<?php

declare(strict_types=1);

$i = 0;
while ($i < 3) {
    echo $i, "\n";
    $i++;
}

do…while

do...while checks after—so it runs at least once.

Staying safe

Avoid infinite loops: ensure something in the loop moves toward the exit condition.

Exercise

Use while to print 0, 1, 2 on three lines (same pattern as the lesson).

From Zero to PHP — Control flow, functions, arrays, and the web