PHP for 循环

如果您已经提前确定脚本运行的次数,可以使用 for 循环。

语法:

for (init counter; test counter; increment counter) {
  code to be executed;
}
解析:
for (初始值; 条件; 增量)
{
    要执行的代码;
}

参数:

init counter:初始化循环计数器的值

test counter:: 评估每个循环迭代。如果值为 TRUE,继续循环。如果它的值为 FALSE,循环结束。

increment counter:增加循环计数器的值

下面的例子显示了从 0 到 10 的数字:

实例:

<?php 
for ($x=0; $x<=10; $x++) {
  echo "The number is:$x <br>";

?>

输出内容:

The number is:0 
The number is:1 
The number is:2 
The number is:3 
The number is:4 
The number is:5 


PHP foreach 循环

foreach 循环只适用于数组,并用于遍历数组中的每个键/值对。


语法

foreach ($array as $value) {
  code to be executed;
}

实例:

<?php 
$colors = array("red","green","blue","yellow"); 
foreach ($colors as $value) {
  echo "$value <br>";
}
?>


输出内容:

red 
green 
blue 
yellow 

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
意见
建议
发表
评论
返回
顶部