PHP While 循环
while, do-while, and the loop control statements break / continue.
while
<?php
$i = 1;
$buf = [];
while ($i <= 5) {
$buf[] = $i;
$i++;
}
echo implode(" ", $buf), "\n";
echo "循环结束后 i = $i\n";1 2 3 4 5
循环结束后 i = 6$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
$j = 10;
do {
echo "执行了一次,j = $j\n";
$j++;
} while ($j < 5);
echo "循环结束,j = $j\n";执行了一次,j = 10
循环结束,j = 11The condition was false from the start, yet the body still ran once — the only difference from while.
break 与 continue
<?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";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
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";找到 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.1may never land; use<or integer counters - **
continuebefore 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.
while
<?php
$i = 1;
$buf = [];
while ($i <= 5) {
$buf[] = $i;
$i++;
}
echo implode(" ", $buf), "\n";
echo "循环结束后 i = $i\n";1 2 3 4 5
循环结束后 i = 6$i 是 6 不是 5——while 是靠条件失败退出的,那次判断已经把 $i 加到 6 了。要保留最后一个有效值,得在循环里另存。do-while
do-while 先执行一次再判断,适合「至少要做一次」的场景,比如重试、读流、菜单循环。
<?php
$j = 10;
do {
echo "执行了一次,j = $j\n";
$j++;
} while ($j < 5);
echo "循环结束,j = $j\n";执行了一次,j = 10
循环结束,j = 11条件一开始就是假的,但循环体还是执行了一次。这就是 do-while 和 while 的唯一区别。
break 与 continue
<?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";1 3 5 7
n = 9注意 $n 最后是 9:8 被 continue 跳过,9 触发 break。continue 只是跳过本次循环剩下的代码,不会跳过 $n++(因为它在前面)。
嵌套循环里的 break 2
break 和 continue 可以带数字,表示跳出几层。
<?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";找到 i=2 j=2
结束break 2 可读性差,容易数错层。多数情况应该把内层循环抽成函数然后 return,意图更清楚。常见死循环
- **忘了
$i++** —— 条件永远成立 - 在循环里重新赋值 ——
while ($row = fetch())里不小心重置了$row - 浮点累加 ——
while ($x != 1.0)用+= 0.1可能永远差一点,改用<或整数计数 - **
continue在自增之前** ——while里continue会跳过末尾的$i++
最后一条最容易中招。while 循环里如果用 continue,一定要把自增写在 continue 之前,或者改用 for。