PHP 8.3.4 Released!

do-while

(PHP 4, PHP 5, PHP 7, PHP 8)

do-whileループは、論理式のチェックが各反復の 最初ではなく最後に行われること以外は、whileループと 全く同じです。通常のwhileループとの主な差は、 do-whileループは最低1回の実行を保証されていることです。 一方、通常のwhileループは、実行されないかもしれません (論理式は各反復の最初でチェックされるので、 最初から値がfalseである場合はループの実行は すぐに終わります)。

do-while ループの構文は次の一つのみです。

<?php
$i
= 0;
do {
echo
$i;
} while (
$i > 0);
?>

上記のループは必ず一度だけ実行されます。その原因は、最初の反復の後、 論理値のチェックを行った際に値が false となり ($i は 0 より大きくない)、ループの実行が終了するためです。

優れたCプログラマは、コードブロック中での実行中止が可能な do-whileループの別の使用法について熟知している かもしれません。 これは、do-while(0)でコードを括り、 break 文を使用する方法です。次のコードは、この方法の例を示しています。

<?php
do {
if (
$i < 5) {
echo
"i は十分大きくはありません。";
break;
}
$i *= $factor;
if (
$i < $minimum_limit) {
break;
}
echo
"iはOKです。";

/* i を処理します */

} while (0);
?>

この技のかわりに goto 演算子を使うこともできます。

add a note

User Contributed Notes 1 note

up
32
jayreardon at gmail dot com
16 years ago
There is one major difference you should be aware of when using the do--while loop vs. using a simple while loop: And that is when the check condition is made.

In a do--while loop, the test condition evaluation is at the end of the loop. This means that the code inside of the loop will iterate once through before the condition is ever evaluated. This is ideal for tasks that need to execute once before a test is made to continue, such as test that is dependant upon the results of the loop.

Conversely, a plain while loop evaluates the test condition at the begining of the loop before any execution in the loop block is ever made. If for some reason your test condition evaluates to false at the very start of the loop, none of the code inside your loop will be executed.
To Top