PHP For循環(huán)
PHP for循環(huán)可用于根據(jù)指定的次數(shù)遍歷一組代碼。愛掏網(wǎng) - it200.com
如果迭代的次數(shù)是已知的,則應(yīng)使用它,否則使用while循環(huán)。愛掏網(wǎng) - it200.com這意味著當(dāng)您已經(jīng)知道要執(zhí)行代碼塊多少次時(shí),可以使用for循環(huán)。愛掏網(wǎng) - it200.com
它允許將所有與循環(huán)相關(guān)的語句放在一個(gè)地方。愛掏網(wǎng) - it200.com請(qǐng)參見下面的語法:
語法
for(initialization; condition; increment/decrement){
//code to be executed
}
參數(shù)
php的for循環(huán)與java/C/C ++的for循環(huán)類似。愛掏網(wǎng) - it200.comfor循環(huán)的參數(shù)具有以下含義:
initialization - 初始化循環(huán)計(jì)數(shù)器的值。愛掏網(wǎng) - it200.comfor循環(huán)的初始值僅執(zhí)行一次。愛掏網(wǎng) - it200.com該參數(shù)為可選參數(shù)。愛掏網(wǎng) - it200.com
condition - 評(píng)估每個(gè)迭代值。愛掏網(wǎng) - it200.com循環(huán)在條件為false時(shí)持續(xù)執(zhí)行。愛掏網(wǎng) - it200.com如果條件為TRUE,則循環(huán)執(zhí)行繼續(xù),否則循環(huán)的執(zhí)行結(jié)束。愛掏網(wǎng) - it200.com
increment/decrement - 增加或減少變量的值。愛掏網(wǎng) - it200.com
流程圖
示例1
<?php
for(n=1;n<=10;n++){
echo "n<br/>";
}
?>
輸出:
1
2
3
4
5
6
7
8
9
10
示例2
所有三個(gè)參數(shù)都是可選的,但分號(hào)(;)在for循環(huán)中是必須的。愛掏網(wǎng) - it200.com如果我們不傳遞參數(shù),它將執(zhí)行無限循環(huán)。愛掏網(wǎng) - it200.com
<?php
i = 1;
//infinite loop
for (;;) {
echoi++;
echo "</br>";
}
?>
輸出:
1
2
3
4
.
.
.
示例3
以下是使用for循環(huán)以四種不同的方式打印數(shù)字1到9的示例。愛掏網(wǎng) - it200.com
<?php
/* example 1 */
for (i = 1;i <= 9; i++) {
echoi;
}
echo "</br>";
/* example 2 */
for (i = 1; ;i++) {
if (i>9) {
break;
}
echoi;
}
echo "</br>";
/* example 3 */
i = 1;
for (; ; ) {
if (i > 9) {
break;
}
echo i;i++;
}
echo "</br>";
/* example 4 */
for (i = 1,j = 0; i <= 9;j += i, printi, $i++);
?>
輸出:
123456789
123456789
123456789
123456789
PHP嵌套循環(huán)
我們可以在PHP中使用嵌套循環(huán),也就是for循環(huán)里面再嵌套for循環(huán)。愛掏網(wǎng) - it200.com內(nèi)部的for循環(huán)只有在外部for循環(huán)的條件為true時(shí)才會(huì)執(zhí)行。愛掏網(wǎng) - it200.com
對(duì)于內(nèi)部或嵌套的for循環(huán)來說,每一個(gè)外部for循環(huán)都完全執(zhí)行一次嵌套的for循環(huán)。愛掏網(wǎng) - it200.com如果外部for循環(huán)要執(zhí)行3次,內(nèi)部for循環(huán)也要執(zhí)行3次,那么內(nèi)部for循環(huán)將會(huì)執(zhí)行9次(第一次外部循環(huán)3次,第二次外部循環(huán)3次,第三次外部循環(huán)3次)。愛掏網(wǎng) - it200.com
示例
<?php
for(i=1;i<=3;i++){
for(j=1;j<=3;j++){
echo "ij<br/>";
}
}
?>
輸出:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
PHP的ForEach循環(huán)
PHP的ForEach循環(huán)用于遍歷數(shù)組元素。愛掏網(wǎng) - it200.com
語法
foreach( array asvar ){
//code to be executed
}
?>
示例
<?php
season=array("summer","winter","spring","autumn");
foreach(season as arr ){
echo "Season is:arr<br />";
}
?>
輸出:
Season is: summer
Season is: winter
Season is: spring
Season is: autumn