Skip to content

PHP While 循环

循环用于重复执行同一段代码块,只要满足特定条件。它们是自动化重复任务的基础结构。

PHP 提供了几种类型的循环来处理不同的场景:

  • while - 只要指定的条件评估为 true,就执行一个代码块。条件在每次迭代之前检查。
  • do...while - 先执行一次代码块,然后只要指定的条件评估为 true,就重复循环。条件在每次迭代之后检查。
  • for - 执行指定次数的代码块。通常在迭代次数已知的情况下使用。
  • foreach - 为数组或对象中的每个元素执行一个代码块。非常适合迭代集合。

本章重点介绍 while 和 do...while 循环。

while 循环是 PHP 中最简单的循环类型。只要其条件保持为 true,它就会迭代执行。

while (condition) { // Code to be executed inside the loop }

工作原理:

  1. 评估 condition。
  2. 如果 condition 为 true,则执行循环内的代码块。
  3. 代码块执行完毕后,控制返回到步骤 1(再次评估条件)。
  4. 如果 condition 为 false,则循环终止,执行继续循环后的紧接着的语句。

示例:从 1 数到 5

<?php
$counter = 1;
while ($counter <= 5) {
echo "The counter is: {$counter}<br>";
$counter++; // 增加计数器 - 避免无限循环的关键!
}
echo "Loop finished!";
?>

输出:

The counter is: 1<br>
The counter is: 2<br>
The counter is: 3<br>
The counter is: 4<br>
The counter is: 5<br>
Loop finished!

重要提示:务必确保 while 循环中的条件最终会变为 false。否则,您将创建一个无限循环 (infinite loop),这可能会导致脚本或服务器冻结。

do...while 循环与 while 循环类似,但有一个关键区别:条件是在代码块执行之后检查。这保证了即使条件最初为 false,代码块也至少会运行一次。

do { // Code to be executed inside the loop } while (condition);

工作原理:

  1. 执行循环内的代码块。
  2. 评估 condition。
  3. 如果 condition 为 true,则控制返回到步骤 1(再次执行代码块)。
  4. 如果 condition 为 false,则循环终止。

示例:代码至少运行一次

<?php
$attempts = 0;
$maxAttempts = 3;
do {
$attempts++;
echo "Attempting connection (Attempt: {$attempts})...<br>";
// 模拟一个可能会失败的连接尝试
$success = ($attempts >= 2); // 假设它在第二次尝试时成功
if ($success) {
echo "Connection successful!<br>";
break; // 如果成功则退出循环
} elseif ($attempts >= $maxAttempts) {
echo "Connection failed after {$maxAttempts} attempts.<br>";
}
} while (!$success && $attempts < $maxAttempts);
?>

循环只运行一次的示例:

<?php
$x = 6;
do {
echo "This will run once. The number is: {$x} <br>";
$x++;
} while ($x <= 5); // 条件在第一次运行后立即变为 false
echo "Loop finished!";
?>

输出:

This will run once. The number is: 6 <br>
Loop finished!

当您需要确保循环体至少执行一次,无论条件的初始状态如何时,请使用 do...while。

for 循环和 foreach 循环提供了不同的迭代控制方式,将在后续章节中介绍。