php数组常见的几种遍历方法

时间:2023-03-08 16:12:01
1、foreach遍历

$arr[] = array('first'=>green,'second'=>'yellow','third'=>'blue');

foreach($arr as $key=>$val){

     echo $key.'-'.$val;

     echo ' ';

}

输出结果:

first-green

second-yellow

third-blue

2、while-each遍历

$arr[] = array('first'=>green,'second'=>'yellow','third'=>'blue');

while($element = each($arr)){

     echo $element ['key'].'-'.$element [value].;

     echo ' ';

}

输出结果:

first-green

second-yellow

third-blue

2、while-list-each遍历

$arr[] = array('first'=>green,'second'=>'yellow','third'=>'blue');

while(list($key,$val) = each($arr)){

     echo $key.'-'.$val;

     echo ' ';

}

输出结果:

first-green

second-yellow

third-blue

注意:以上遍历中的each()函数,数组将记录当前元素,若要重新遍历数组,则要使用reset()函数重新设置数组指针到数组的开始处。