There are many ways to implement array traversal:
1. Continuously indexed array:
It is very simple to implement continuous array traversal, because the index of the array is continuous (0 1 2...), so we can first use the count() function to calculate the number of elements in the array, and then create a for loop, As follows:
$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");
}
The result is:
Maths
English
physics
Here we assign an initial value of 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; //Pay attention here
for ($i=3;$i<$num_elements; ++$i){
echo ("$subject[$i]
n");
}
Here $i is assigned a value of 3, and $num_elements=count($subject)+3. This is easily overlooked.
2. Array of non-consecutive indexes:
$subject=array("m"=>"maths","e"=>"english","p"=>"physics");
An array is created here with the index values "m" "e " "p" respectively. How to traverse such an array?
Method 1: Use list() and each() function combination
$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 foreach statement
$subject=array("m"=>"maths","e"=>"english","p"=>"physics");
foreach($subject as $key => $value){
echo "$key is $value
n";
}
?>
Isn’t it simpler than list() and each()?
The difference between foreach and list() each() combination:
Foreach performs operations on a copy of the original array. Its advantage is that it will not affect the position of the current array pointer. Its disadvantage is that for a large array, copying takes a long time.
List() each() combination It is obvious that after traversing and using it, the position of the pointer changes.
Method 3: Use the array_walk() function to traverse the array
Array_walk() allows users to customize functions to process each element in the array.
$subject=array("maths","english","physics");
Function printElement($element){
print ("$element
n");
}
array_walk($subject,"printElement");
The above is the method of traversing arrays in PHP introduced to you by Bangkejia.com. I hope it will be helpful to you.