Php to traverse the array. There are multiple ways to traverse arrays: 1. arrays with continuous indexes: it is very easy to traverse arrays with continuous indexes because the indexes of arrays are continuous (012 ), so we can first use count to traverse the array. there are multiple implementation methods:
1. arrays of continuous indexes:
It is very easy to traverse continuous arrays, because the index of the array is continuous (0 1 2 ......), Therefore, we can use the count () function to calculate the number of elements in the array, and then create a for loop, as shown below:
$ Subject = array ("maths", "english", "physics ");
$ Num_elements = count ($ subject); // The value of $ num_elements is 3.
For ($ I = 0; $ I <$ num_elements; ++ $ I ){
Echo ("$ subject [$ I]
N ");
}
Result:
Maths
English
Physics
Here, we assign the initial value 0 to $ I because the index of the array element is 0 1 2 by default. if the index of the first element is not 0, we only need:
$ Subject = array (3 => "maths", "english", "physics ");
$ Num_elements = count ($ subject) + 3; // note the following:
For ($ I = 3; $ I <$ num_elements; ++ $ I ){
Echo ("$ subject [$ I]
N ");
}
$ I is assigned a value of 3 and $ num_elements = count ($ subject) + 3, which is easily ignored here.
2. arrays with non-continuous indexes:
$ Subject = array ("m" => "maths", "e" => "english", "p" => "physics ");
Here an array is created, and the index values are "m" e "" p ". how can we traverse such an array?
Method 1: Use the combination of list () and each () functions
$ Subject = array ("m" => "maths", "e" => "english", "p" => "physics ");
Reset ($ subject); // reset the pointer to the first element.
While (list ($ key, $ value) = each ($ subject )){
Echo "$ key is $ value
N ";}
Method 2: Use the foreach statement
$ Subject = array ("m" => "maths", "e" => "english", "p" => "physics ");
Foreach ($ subject as $ key => $ value ){
Echo "$ key is $ value
N ";
}
?>
Is it simpler than list () and each.
The differences between foreach and list () each () combinations are as follows:
Foreach performs operations on the original array copy. Its advantage is that it does not affect the position of the current array pointer, but it takes a long time to copy a large array.
The combination of list () each () is obviously traversed by him. after that, the pointer position is changed.
Method 3: Use the array_walk () function to traverse the array.
Array_walk () allows users to customize functions to process every element in the array.
$ Subject = array ("maths", "english", "physics ");
Function printElement ($ element ){
Print ("$ element
N ");
}
Array_walk ($ subject, "printElement ");
The above is the array traversal method in php introduced to you by Home.com. I hope it will help you.
Rows 1. continuous index array: it is very easy to traverse the continuous array, because the index of the array is continuous (0 1 2), so we can first use count...