Home > Article > Backend Development > php array traversal
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]; } ?>
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.':'.$value.'</br>'; } ?>
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.':'.$value.'</br>'; } ?>
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.