In php, the most used method for Array traversal is foreac, while, and for. Let's introduce the program code for these three methods.
I am often asked if the PHP array is accessed using foreach, is the traversal order fixed? In what order does it traverse?
For example:
The Code is as follows: |
Copy code |
<? Php $ arr ['laruence '] = 'huixinchen '; $ Arr ['yahoo '] = 2007; $ Arr ['baidu'] = 2008; Foreach ($ arr as $ key => $ val) { // What is the result? }
|
For example:
The Code is as follows: |
Copy code |
<? Php $ Arr [2] = 'huixinchen '; $ Arr [2] = 2007; $ arr [0] = 2008; Foreach ($ arr as $ key => $ val) { // What is the current result? } |
When we use functions of the each/next series to traverse, we also implement sequential traversal by moving the internal pointer of the array. Here is a problem, for example:
The Code is as follows: |
Copy code |
<? Php $ Arr = array (1, 2, 3, 4, 5 ); Foreach ($ arr as $ v) {// available} While (list ($ key, $ v) = each ($ arr )) {// Cannot be obtained} ?> |
After learning about the knowledge I just introduced, this problem will be very clear, because foreach will automatically reset, while this part will not reset, so after foreach ends, pInternalPointer points to the end of the array, the while statement block cannot be accessed. The solution is to reset the internal pointer of the array before each.
That is to say, the order of traversing arrays in PHP is related to the addition of elements. Now we know clearly that the output of the problem at the beginning of the article is:
Huixinchen
2007
2008
Therefore, if you want to traverse the array of numeric indexes by index size, you should use for instead of foreach.
The Code is as follows: |
Copy code |
For ($ I = 0, $ l = count ($ arr); $ I <$ l; $ I ++)
|
{// At this time, it cannot be considered sequential traversal (linear traversal )}