ZetCode

PHP do-while 循环

最后修改于 2025 年 4 月 16 日

PHP do-while 循环是一种控制结构,它至少执行一次代码块,然后在条件为真时重复执行。 与普通的 while 循环不同,do-while 循环在每次迭代后检查条件。

基本定义

关键字 do 启动一个 do-while 循环,该循环始终至少执行其代码块一次。 在每次迭代后检查 while 条件,以确定是否应该继续循环。

语法:do { code } while (condition);。 条件是任何计算结果为布尔值 true 或 false 的表达式。 注意 while 条件后的分号。

当您需要在检查条件之前执行代码时,do-while 循环很有用。 它们通常用于输入验证和菜单系统。

基本 do-while 循环

此示例演示了一个简单的 do-while 循环,从 1 数到 5。

basic_do_while.php
<?php

declare(strict_types=1);

$i = 1;

do {
    echo $i . " ";
    $i++;
} while ($i <= 5);

代码将 $i 初始化为 1。 循环打印该值并递增它。 条件检查 $i 是否小于或等于 5。 循环正好运行 5 次,打印数字 1 到 5。

保证首次执行

此示例展示了 do-while 如何始终至少执行一次。

guaranteed_execution.php
<?php

declare(strict_types=1);

$count = 10;

do {
    echo "This runs once, even though count is $count";
} while ($count < 5);

尽管条件最初为假,但循环执行一次。 这演示了与常规 while 循环的关键区别。 仅在第一次迭代后才检查条件。

用户输入验证

此示例使用 do-while 来验证用户输入。

input_validation.php
<?php

declare(strict_types=1);

do {
    $input = (int) readline("Enter a number between 1-10: ");
} while ($input < 1 || $input > 10);

echo "Valid input: $input";

代码提示输入,直到输入 1-10 之间的有效数字。 循环在输入无效时继续。 这种模式确保用户至少获得一次提示,并继续直到输入有效。

菜单系统

此示例使用 do-while 实现一个简单的菜单系统。

menu_system.php
<?php

declare(strict_types=1);

do {
    echo "1. Option 1\n";
    echo "2. Option 2\n";
    echo "3. Exit\n";
    
    $choice = (int) readline("Select: ");
    
    switch ($choice) {
        case 1: echo "Option 1 selected\n"; break;
        case 2: echo "Option 2 selected\n"; break;
    }
} while ($choice != 3);

echo "Goodbye!";

循环显示菜单并处理用户选择。 它一直持续到用户选择选项 3(退出)。 菜单始终至少显示一次。 Switch 语句通常与菜单系统配合使用。

数组处理

此示例使用 do-while 处理数组元素。

array_processing.php
<?php

declare(strict_types=1);

$colors = ["red", "green", "blue"];
$index = 0;

do {
    echo strtoupper($colors[$index]) . "\n";
    $index++;
} while ($index < count($colors));

代码处理 $colors 数组中的每个元素。 它将每种颜色转换为大写并打印出来。 循环在索引小于数组长度时继续。 注意检查数组边界。

嵌套 do-while 循环

此示例演示了用于乘法表的嵌套 do-while 循环。

nested_loops.php
<?php

declare(strict_types=1);

$i = 1;

do {
    $j = 1;
    do {
        echo ($i * $j) . "\t";
        $j++;
    } while ($j <= 10);
    
    echo "\n";
    $i++;
} while ($i <= 10);

外部循环控制行,而内部循环处理列。 它打印一个 10x10 的乘法表。 每个内部循环在外部循环前进之前完全完成。 嵌套循环可以创建网格模式。

Break 和 Continue

此示例显示如何在 do-while 循环中使用 break 和 continue。

break_continue.php
<?php

declare(strict_types=1);

$num = 0;

do {
    $num++;
    
    if ($num % 2 == 0) {
        continue; // Skip even numbers
    }
    
    echo "$num ";
    
    if ($num >= 9) {
        break; // Exit loop at 9
    }
} while (true);

echo "\nLoop ended at $num";

循环使用 continue 跳过偶数,打印奇数。 当达到 9 时它会中断,尽管条件始终为真。 Break 立即退出循环,而 continue 跳到下一个迭代。

最佳实践

来源

PHP do-while 文档

本教程介绍了 PHP do-while 循环,并提供实用示例,展示了基本用法、输入验证、菜单系统和控制流程。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有十多年的编程教学经验。

列出 所有 PHP 教程