PHP While 循环

while, do-while, and the loop control statements break / continue.

Beginner
Key Points`while` tests first; `do-while` always runs at least once.

while

PHP
<?php
$i = 1;
$buf = [];

while ($i <= 5) {
    $buf[] = $i;
    $i++;
}

echo implode(" ", $buf), "\n";
echo "循环结束后 i = $i\n";
Output
1 2 3 4 5
循环结束后 i = 6
After the loop $i is 6, not 5 — the failing condition already incremented it. Store the last valid value inside the loop if you need it.

do-while

do-while runs the body then tests — good for retry loops, stream reads, menus.

PHP
<?php
$j = 10;

do {
    echo "执行了一次,j = $j\n";
    $j++;
} while ($j < 5);

echo "循环结束,j = $j\n";
Output
执行了一次,j = 10
循环结束,j = 11

The condition was false from the start, yet the body still ran once — the only difference from while.

break 与 continue

PHP
<?php
$n = 0;
$buf = [];

while (true) {
    $n++;
    if ($n % 2 === 0) {
        continue;          // 跳过偶数
    }
    if ($n > 7) {
        break;             // 超过 7 就停
    }
    $buf[] = $n;
}

echo implode(" ", $buf), "\n";
echo "n = $n\n";
Output
1 3 5 7
n = 9

$n ends at 9: 8 was skipped by continue, 9 hit break. continue only skips the rest of the body, not the increment that already ran.

break 2 in nested loops

break and continue accept a level count.

PHP
<?php
for ($i = 1; $i <= 3; $i++) {
    for ($j = 1; $j <= 3; $j++) {
        if ($i * $j === 4) {
            echo "找到 i=$i j=$j\n";
            break 2;       // 直接跳出两层
        }
    }
}
echo "结束\n";
Output
找到 i=2 j=2
结束
break 2 is hard to read and easy to miscount. Usually extract the inner loop into a function and return.

Common infinite loops

  • **Forgot $i++** —— the condition never fails
  • Reassigning inside —— resetting the loop variable
  • Float accumulation —— while ($x != 1.0) with += 0.1 may never land; use < or integer counters
  • **continue before the increment** —— skips $i++ at the loop tail

The last one bites most often. Inside a while, either increment before continue or switch to for.

Friends & Partners