while

while 循環是 PHP 中最簡單的循環型別。它和 C 語言中的 while 表現得一樣。while 語句的基本格式是:

while (expr) statement

while 語句的含意很簡單,它告訴 PHP 只要while 表達式的值為 TRUE 就重複執行嵌套中的循環語句。表達式的值在每次開始循環時檢查,所以即使這個值在循環語句中改變了,語句也不會停止執行,直到本次循環結束。有時候如果 while 表達式的值一開始就是 FALSE,則循環語句一次都不會執行。

if 語句一樣,可以在 while 循環中用大括號括起一個語句組,或者用替代語法:

while (expr): statement ... endwhile;

下面兩個例子完全一樣,都顯示數字 1 到 10:

/* example 1 */

$i = 1;
while ($i <= 10) {
    print $i++;  /* the printed value would be
                    $i before the increment
                    (post-increment) */
}

/* example 2 */

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