PHP While Loop

PHP While Loop

Loops execute the same block of code repeatedly. The while and do…while loops run as long as a condition is true.

1 - While Loop

$i = 1;
while ($i <= 5) {
    echo "Number: $i <br>";
    $i++;
}

2 - Do…While Loop

Executes the block at least once before checking the condition.

$i = 1;
do {
    echo "Number: $i <br>";
    $i++;
} while ($i <= 5);

3 - Break and Continue

$i = 0;
while ($i < 10) {
    $i++;
    if ($i % 2 === 0) continue; // skip even numbers
    if ($i === 7) break;        // stop at 7
    echo $i . " ";
}
// Output: 1 3 5

4 - Practical Example — Reading a File

$handle = fopen("data.txt", "r");
while (!feof($handle)) {
    $line = fgets($handle);
    echo $line . "<br>";
}
fclose($handle);

Note: Always make sure the loop condition will eventually become false — an infinite loop will freeze or crash the server process.

-Tip-