while

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

whileループは、PHPで最も簡単なタイプのループです。 このループは、CのWHILEループと同様の動作をします。 whileループの基本形は次のようになります。

while (式)
    文

while文の意味は簡単です。 while文は、式の値がtrueである間、 入れ子の文を繰り返し実行することをPHPに指示します。 式の値は各反復処理の開始時にチェックされるので、ループ内の文の実行により この値が変わった場合でもループ実行は各ループを終るまで終わりません。 (PHPによるループ内の文の実行が1回分の反復に相当します) while式の値がはじめからfalseの 場合は、内部の文は一回も実行されません。

if文と同様に、波括弧で複数の文を囲うか、 以下に示す別の構文を用いることにより、同じwhile ループの中に複数の文をグループ化することができます。

while (式):
    文
    ...
endwhile;

次の例は同じです。どちらも 1 から 10 までの数を出力します。

<?php
/* 例 1 */

$i = 1;
while (
$i <= 10) {
echo
$i++; /* 出力される値は、足される前の
$iの値です。
(後置加算) */
}

/* 例 2 */

$i = 1;
while (
$i <= 10):
echo
$i;
$i++;
endwhile;
?>

add a note

User Contributed Notes 3 notes

up
-16
razvan_bc at yahoo dot com
1 year ago
assuming you want to have another way to archieve
<?php

for($i=10;$i>0;$i--){
echo
$i.'<br>';
}

?>

then yo have this:

<?php

$v
=10;
do{
echo
$v.'<br>';
}while(--
$v);

/*
while(--$v) : 10...1 , when $v==0 stops
*/

?>
up
-44
Dan Liebner
2 years ago
While loops don't require a code block (statement).

<?php

while( ++$i < 10 ); // look ma, no brackets!

echo $i; // 10

?>
up
-45
mparsa1372 at gmail dot com
2 years ago
The example below displays the numbers from 1 to 5:

<?php
$x
= 1;

while(
$x <= 5) {
echo
"The number is: $x <br>";
$x++;
}
?>

This example counts to 100 by tens:

<?php
$x
= 0;

while(
$x <= 100) {
echo
"The number is: $x <br>";
$x+=10;
}
?>
To Top