PHP for循环

PHP for循环可以用来遍历一组指定的次数的代码。如果迭代次数已知,则应优先考虑使用for循环,否则使用while循环。
for循环的语法

for(initialization; condition; increment/decrement){  
    //code to be executed  
}

for循环流程图

示例代码-

<?php  
    for($n=1;$n<=10;$n++){  
        echo "$n<br/>";  
    }  
?>

输出结果如下-

1
2
3
4
5
6
7
8
9
10

PHP嵌套for循环

在PHP中,我们可以在for循环中使用for循环,它称为嵌套for循环。
在内部或嵌套for循环的情况下,对于每一次执行的外部for循环,将完全执行嵌套的内for循环。 如果外部for循环执行3次,内部for循环执行3次,内部for循环将一共要执行9次(第一个外部for循环为3次,第二个内for部循环为3次)。

示例

<?php  
for($i=1;$i<=3;$i++){  
    for($j=1;$j<=3;$j++){  
        echo "$i   $j<br/>";  
    }  
}  
?>

上面代码输出结果如下 -

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

PHP foreach循环

PHP中的foreach循环循环用于遍历数组元素。

语法

<?php
foreach( $array as $var ){  
 //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

上一篇: PHP Switch语句 下一篇: PHP while循环