Home > Backend Development > PHP Tutorial > php array traversal

php array traversal

巴扎黑
Release: 2016-11-22 11:29:19
Original
1232 people have browsed it

Let’s talk about the traversal of PHP arrays. Many people may question, what is there to say about traversing arrays? A for loop will just come out. In fact, it is not the case. A for loop traversing PHP arrays is the worst PHP code. The comparison is detailed below. Analyze.

We all know that C++ and C# will allocate a continuous fixed-size memory space in the stack area to the array variable when defining an array. C++ generally uses a for loop to increment the offset to traverse the array; in addition to the for loop, C# can also use foreach to traverse the array. ;What about php? ? We often see the following code:

<?php
$arr = array(
0=>"zxp",
1=>"male",
2=>"北京西三旗"
);
for($i=0;$i<count($arr);$i++)
{
echo $arr[$i];
}
?>
Copy after login

This kind of code is fine for the time being, but its fault tolerance is very low and its robustness is very poor, so it can go wrong accidentally. PHP arrays are not a continuous memory space, and continuous offsets cannot be used to traverse the array, and PHP arrays are scalable. For example, if the above code $arr inserts an element $arr[5]=5, the for loop must have gone wrong.

        PHP array traversal uses foreach and while. These two traversal methods are given below

<?php
$arr = array(
//"comment"=>"personal information",
0=>"zxp",
1=>"male",
"age"=>29,
2=>"北京西三旗"
);
$arr[4] = "高级开发工程师";
foreach ($arr as $key => $value) {
echo $key.&#39;:&#39;.$value.&#39;</br>&#39;;
}
?>
Copy after login

As in the above code, the traversal is handed over to foreach. For the array elements traversed, the key name is assigned to $key and the value is assigned to $ value.

<?php
$arr = array(
0=>"zxp",
1=>"male",
"age"=>29,
2=>"北京西三旗"
);
reset($arr);
while (list($key,$value) = each($arr))
{
echo $key.&#39;:&#39;.$value.&#39;</br>&#39;;
}
?>
Copy after login

In the above code, the array traversal is handed over to the each function. When using a while loop plus list operation plus each function to traverse the php array, you must pay attention: before the while loop, call the reset function to point the array pointer to the first element. Otherwise, you will find that the number of elements traversed is not enough.

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