Comparison of several single-dimensional array traversal methods in PHP

高洛峰
Release: 2023-03-01 13:16:01
Original
936 people have browsed it

The code is as follows:

<?php 
//a 
$arr=array(&#39;a&#39;=>&#39;abc&#39;,&#39;b&#39;=>123,&#39;c&#39;=>true); 
//b 
//$arr=range(&#39;a&#39;,&#39;d&#39;); 
//1 
for($i=0;$i<sizeof($arr);$i++) 
echo $arr[$i].&#39;, &#39;; 
echo &#39;<br />&#39;; 
//2 
foreach($arr as $key) 
echo "$key, "; 
echo &#39;<br />&#39;; 
//3 
foreach($arr as $key=>$val) 
echo "$key-$val, "; 
echo &#39;<br />&#39;; 
//4 
reset($arr); 
while($item=each($arr)){ 
echo $item[&#39;key&#39;].&#39;-&#39;.$item[&#39;value&#39;].&#39;, &#39;; 
} 
echo &#39;<br />&#39;; 
//5 
reset($arr); 
while(list($key,$val)=each($arr)){ 
echo "$key-$val, "; 
} 
echo &#39;<br />&#39;; 
?>
Copy after login

Use the statement a $arr=array('a'=>'abc','b'=>123,'c'=>true); to initialize $arr to get the number 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 numeric indexes; after the for and foreach traversal, the data does not need to be reset() to be available for the next traversal, while the each method does.

Related labels:
php
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