while

while 迴圈是 PHP 中最簡單的迴圈類型。它和 C 語系中的 while 表現得一樣。while 語句的基本格式是:

while (expr)
    statement

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

if 語句一樣,可以在 while 迴圈中用花括號括起一個語句組,或是用替代語法:

while (expr):
    statement
    ...
endwhile;

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

<?php
/* example 1 */

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

/* example 2 */

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