In the process of encoding, iterating over the specified array is a common thing. In the process of traversal, many languages use the For loop to traverse, convenient and quick. But in PHP, the subscript for arrays differs from some languages. The subscript of an array in PHP can be a string, or it can be mixed with a string and a number, which is known as an associative array. If the subscript is a pure number, that is the index array.
1.for ()
for () traversal, there is a limitation, if it is an associative array, it can not be based on the increment of the subscript to traverse, suddenly popped out of the string, will definitely error. So in PHP, the range that the for () can use is the index array.
<?php $arr []= "User"; $arr []=25; $arr []= "man"; Print array echo "<pre>"; Print_r ($arr); echo "</pre>"; Iterate over the array for ($i =0; $i <count ($arr); $i + +) {echo $arr [$i]. " <br> "; }?>
2.foreach ()
foreach () Traversal this way in PHP is the best way to be male and female, whether you are a number or a string, brother does not see you subscript add one, is a dry come over. And it's important to be simple and efficient.
<?php $arr ["Name"]= "user"; $arr ["Age"]=25; $arr ["Sex"]= "man"; $arr []= "Teacher"; Print array echo "<pre>"; Print_r ($arr); echo "</pre>"; Iterate over the array foreach ($arr as $val) {echo $val. <br> "; }?>
If you need to print key-value pairs, make a slight change to foreach ().
Iterate over the array foreach ($arr as $key + = $val) {echo $key. ":". $val. " <br> ";}
3.while (List () =each ())
The clever comparison of this way, with the frequency is not very high, but when looking at the code to meet it, at least to be able to understand the line AH. It's better to master it, just a little bit of trouble.
<?php $arr ["Name"]= "user"; $arr ["Age"]=25; $arr ["Sex"]= "man"; $arr []= "Teacher"; Print array echo "<pre>"; Print_r ($arr); echo "</pre>"; Iterate through the array while (list ($key, $val) =each ($arr)) {echo $key. ': '. $val. ' <br> "; }?>
The above example code is a one-dimensional array, if you want to two-dimensional, three-dimensional or even higher-dimensional array to traverse, it has been nested add an if statement. Generally used more is a two-dimensional array, I think there is no one has to write a 10-dimensional array, if so, the time of traversal, that taste is not the general sour cool.