PHP——迴圈語句
阿新 • • 發佈:2021-01-20
while
只要指定條件為真,則迴圈程式碼塊
語法
while (條件為真) {
要執行的程式碼;
}
do...while
先執行一次程式碼塊,然後指定條件為真則重複迴圈
語法
do {
要執行的程式碼;
} while (條件為真);
while與do...while的差別在判斷條件不成立時(初次),do...while還會執行語句。
<?php header("content-type:text/html;charset=utf-8"); $a = 19; while ($a<6) { echo "數字是:$a <br/>"; echo "while"; $a++; } do { echo "數字是:$a <br/>"; echo "do...while"; $a++; } while ($a<6) ?>
for
迴圈程式碼塊指定次數
語法
for (init counter; test counter; increment counter) {
code to be executed;
}
引數
- init counter:初始化迴圈計數器的值 (初始值)
- test counter:評估每個迴圈迭代。如果值為 TRUE,繼續迴圈。如果它的值為 FALSE,迴圈結束。(判斷條件)
- increment counter:增加迴圈計數器的值
舉個例子
<?php header("content-type:text/html;charset=utf-8"); for ($a=0; $a<10; $a++) { echo "數字是:$a<br/>"; } ?>
foreach
只適用於陣列,遍歷陣列中的每個元素並迴圈程式碼塊
語法
foreach ($array as $value)
{
code to be executed;
}
引數
- $array:陣列的變數名
- $value:接受陣列值的變數名
<?php
$colors =array("red","green","yellow","blue");
foreach ($colors as $tmp)
{
echo "$tmp <br/>";
}
?>