Home > Backend Development > PHP Tutorial > php若干单维数组遍历方法的比较_PHP

php若干单维数组遍历方法的比较_PHP

WBOY
Release: 2016-06-01 12:14:30
Original
688 people have browsed it
复制代码 代码如下:
//a
$arr=array('a'=>'abc','b'=>123,'c'=>true);
//b
//$arr=range('a','d');
//1
for($i=0;$iecho $arr[$i].', ';
echo '
';
//2
foreach($arr as $key)
echo "$key, ";
echo '
';
//3
foreach($arr as $key=>$val)
echo "$key-$val, ";
echo '
';
//4
reset($arr);
while($item=each($arr)){
echo $item['key'].'-'.$item['value'].', ';
}
echo '
';
//5
reset($arr);
while(list($key,$val)=each($arr)){
echo "$key-$val, ";
}
echo '
';
?>

使用语句a $arr=array('a'=>'abc','b'=>123,'c'=>true); 对$arr进行初始化得到数字索引数组,输出如下:
, , ,
abc, 123, 1,
a-abc, b-123, c-1,
a-abc, b-123, c-1,
a-abc, b-123, c-1, 使用语句b $arr=range('a','d'); 对$arr进行初始化得到关联数组,输出如下:
a, b, c, d,
a, b, c, d,
0-a, 1-b, 2-c, 3-d,
0-a, 1-b, 2-c, 3-d,
0-a, 1-b, 2-c, 3-d, for循环只对数字索引有限;for和foreach遍历结束后不需要对数据进行reset()操作即可供下次遍历,而each方法则需要。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template