PHP 迴圈 - While 迴圈
迴圈執行代碼塊指定的次數,或者當指定的條件為真時迴圈執行代碼塊。
PHP 迴圈
在您編寫代碼時,您經常需要讓相同的代碼塊一次又一次地重複運行。我們可以在代碼中使用迴圈語句來完成這個任務。
在 PHP 中,提供了下列迴圈語句:
- while - 只要指定的條件成立,則迴圈執行代碼塊
- do...while - 首先執行一次代碼塊,然後在指定的條件成立時重複這個迴圈
- for - 迴圈執行代碼塊指定的次數
- foreach - 根據數組中每個元素來迴圈代碼塊
while 迴圈
while 迴圈將重複執行代碼塊,直到指定的條件不成立。
語法
while (條件) { 要執行的代碼; }
實例
下麵的實例首先設置變數 i 的值為 1 ($i=1;)。
然後,只要 i 小於或者等於 5,while 迴圈將繼續運行。迴圈每運行一次,i 就會遞增 1:
<html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br>"; $i++; } ?> </body> </html>
輸出:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 2
The number is 3
The number is 4
The number is 5
do...while 語句
do...while 語句會至少執行一次代碼,然後檢查條件,只要條件成立,就會重複進行迴圈。
語法
do { 要執行的代碼; } while (條件);
實例
下麵的實例首先設置變數 i 的值為 1 ($i=1;)。
然後,開始 do...while 迴圈。迴圈將變數 i 的值遞增 1,然後輸出。先檢查條件(i 小於或者等於 5),只要 i 小於或者等於 5,迴圈將繼續運行:
<html> <body> <?php $i=1; do { $i++; echo "The number is " . $i . "<br>"; } while ($i<=5); ?> </body> </html>
輸出:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 3
The number is 4
The number is 5
The number is 6
for 迴圈和 foreach 迴圈將在下一章進行講解。