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

WBOY
Release: 2016-07-21 15:24:54
Original
930 people have browsed it

复制代码代码如下:

//a
$arr=array('a'=>'abc','b'=>123,'c'=>true);
//b
//$arr=range('a','d');
//1
for($i=0;$i echo $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方法则需要。

www.bkjia.com true http://www.bkjia.com/PHPjc/324212.html TechArticle 复制代码 代码如下: ?php //a $arr=array('a'='abc','b'=123,'c'=true); //b //$arr=range('a','d'); //1 for($i=0;$isizeof($arr);$i++) echo $arr[$i].', '; echo 'br /'; //2 foreac...
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!