Comparison of several single-dimensional array traversal methods in PHP_PHP tutorial

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

Copy code The code is as follows:

//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 '
';
?>

Use Statement a $arr=array('a'=>'abc','b'=>123,'c'=>true); Initialize $arr to get the numeric index array, the output is as follows:
, , ,
abc, 123, 1,
a-abc, b-123, c-1,
a-abc, b-123, c-1,
a-abc, b -123, c-1, use statement b $arr=range('a','d'); to initialize $arr to get the associative array, the output is as follows:
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, the for loop only has limited numerical indexes; for and foreach do not need to reset() the data after the traversal is completed to make it available for the next traversal, while the each method does .

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324212.htmlTechArticleCopy the code as follows: ?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
Popular Tutorials
More>
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!