PHP for 循環執行代碼塊指定的次數。
如果您已經提前確定腳本運行的次數,可以使用 for 循環。
for (init counter; test counter; increment counter) {
code to be executed;
}
參數:
下面的例子顯示了從 0 到 10 的數字:
<!DOCTYPE html>
<html>
<body>
<?php
for ($x=0; $x<=10; $x++) {
echo "數字是:$x <br>";
}
?>
</body>
</html>
數字是:0
數字是:1
數字是:2
數字是:3
數字是:4
數字是:5
數字是:6
數字是:7
數字是:8
數字是:9
數字是:10
foreach 循環只適用於數組,並用於遍歷數組中的每個鍵/值對。
foreach ($array as $value) {
code to be executed;
}
每進行一次循環迭代,當前數組元素的值就會被賦值給 $value 變量,並且數組指針會逐一地移動,直到到達最後一個數組元素。
下面的例子演示的循環將輸出給定數組($colors)的值:
<!DOCTYPE html>
<html>
<body>
<?php
$colors = array("red","green","blue","yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
</body>
</html>
red
green
blue
yellow