《PHP 循環-While 循環》要點:
本文介紹了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
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
歡迎參與《PHP 循環-While 循環》討論,分享您的想法,維易PHP學院為您提供專業教程。