长乐王
长乐王

PHP循环遍历数组的几种方法

一、foreach():foreach()是一个用来遍历数组中数据的最简单有效的方法。

$colors = array("red","green","blue","yellow");
foreach($colors as $value){
    echo "The color is $value <br>";
}
#输出内容
/**
The color is red
The color is green
The color is blue
The color is yellow
**/

二、for():使用for语句循环遍历数组,数组必须是索引数组。

$colors = array("red","green","blue","yellow");
for($i=0; $i<count($colors); $i++){ 
    $value= $colors[$i]; 
    echo "The color is $value <br>";
}
#输出内容
/**
The color is red
The color is green
The color is blue
The color is yellow
**/

三、while()和list(),each()配合使用:

$colors = array("red","green","blue","yellow");
while(list($key,$value) = each($colors)){ 
    echo "The color is $value <br>";
}
#输出内容
/**
The color is red
The color is green
The color is blue
The color is yellow
**/
本文番号: 长乐王 - 前端开发 - PHP循环遍历数组的几种方法

评论