當不知道確切迭代次數、僅根據條件判斷是否繼續時,while 和 do-while 是最佳選擇。
while (條件) {
// 循環體
}
條件為 true 才執行循環體,可能一次都不執行。
<?php
$i = 1;
while ($i <= 5) {
echo "The number is $i <br>";
$i++;
}
?>
do {
// 循環體
} while (條件);
至少執行一次,然後檢查條件決定是否繼續。
<?php
$i = 1;
do {
$i++;
echo "The number is $i <br>";
} while ($i <= 5);
?>
輸出:
The number is 2 The number is 3 The number is 4 The number is 5 The number is 6
| 循環類型 | 適用場景 |
|---|---|
for | 已知迭代次數、需要計數器控制 |
foreach | 遍歷陣列/物件、不需手動管理指針 |
while | 未知迭代次數、可能零次執行 |
do-while | 未知迭代次數、至少需執行一次 |
false(如忘記遞增計數器)do-while 末尾分號 ; 不可省略