while

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

while 循环是 PHP 中最简单的循环类型。它和 C 语言中的 while 表现地一样。while 语句的基本格式是:

while (expr)
    statement

while 语句的含意很简单,它告诉 PHP 只要 while 表达式的值为 true 就重复执行嵌套中的循环语句。表达式的值在每次开始循环时检查,所以即使这个值在循环语句中改变了,语句也不会停止执行,直到本次循环结束。 如果 while 表达式的值一开始就是 false,则循环语句一次都不会执行。

if 语句一样,可以在 while 循环中用花括号括起一个语句组,或者用替代语法:

while (expr):
    statement
    ...
endwhile;

下面两个例子完全一样,都显示数字 1 到 10:

<?php
/* 示例 1 */

$i = 1;
while (
$i <= 10) {
echo
$i++; /* 在自增前(后自增)打印的值将会是 $i */
}

/* 示例 2 */

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

add a note

User Contributed Notes 4 notes

up
-12
razvan_bc at yahoo dot com
10 months 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
-39
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
-48
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;
}
?>
up
-66
er dot sarimkhan786 at gmail dot com
7 years ago
simple pyramid pattern program using while loop
<?php
$i
=1;
while(
$i<=5)
{
   
$j=1;
    while(
$j<=$i)
    {
      echo
"*&nbsp&nbsp";
     
$j++;     
    }
    echo
"<br>";
   
$i++;
}
?>
// or alternatively you can use:
<?php
$i
=1;
while(
$i<=5):

   
$j=1;
    while(
$j<=$i):
      echo
"*&nbsp&nbsp";
     
$j++;     
    endwhile;
   
    echo
"<br>";
   
$i++;
endwhile;
?>
To Top