iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP While Loops

while loops repeat code while a condition is true. PHP also has do-while, foreach, and the classic for.

while and friends

EXAMPLE
<?php
// 1. while - check condition BEFORE each iteration
$i = 0;
while ($i < 5) {
    echo $i;
    $i++;
}

// 2. do-while - check AFTER (body runs at least once)
$i = 0;
do {
    echo $i;
    $i++;
} while ($i < 5);

// 3. classic for
for ($i = 0; $i < 5; $i++) {
    echo $i;
}

// 4. foreach over an array
$colors = ['red', 'green', 'blue'];
foreach ($colors as $c) {
    echo $c;
}

// foreach with keys
$user = ['name' => 'Ada', 'email' => 'ada@example.com'];
foreach ($user as $key => $value) {
    echo "$key: $value\n";
}

// 5. break + continue
foreach ($items as $item) {
    if ($item['archived']) continue;       // skip archived
    if ($item['fatal'])    break;          // stop entirely
    process($item);
}

// 6. Common patterns

// Read a file line by line
$h = fopen('big.log', 'r');
while (($line = fgets($h)) !== false) {
    process($line);
}
fclose($h);

// Pagination loop
$page = 1;
do {
    $results = api_fetch($page);
    foreach ($results as $r) save($r);
    $page++;
} while (count($results) === 100);

// Polling with backoff
$delay = 1;
while (!is_ready()) {
    sleep($delay);
    $delay = min($delay * 2, 60);  // cap at 60s
}

// 7. Avoid infinite loops
$attempts = 0;
while (!success() && $attempts < 5) {
    try_once();
    $attempts++;
}

Why it matters

foreach is the workhorse for arrays. while is for unknown counts (file reads, polling). Always set a hard cap on retries to avoid infinite loops; production code should never use while (true) without an explicit break condition.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
<?php
$n = 0;
while ($n < 5) {
    echo $n, PHP_EOL;
    $n++;
}
Try it Yourself »

Exercise

Run body at least once with this loop form.

{ ... } while ($go);

Test yourself

Q1. do-while differs from while because…
Q2. Endless loop is…
Q3. "endwhile" exists for…

Discussion

Loading…