Home >Backend Development >PHP Tutorial >Summary of PHP array traversal statements (foreach, for, list, each)_PHP tutorial
When using foreach to access, is the order of traversal fixed? In what order should it be traversed?
For example:
The code is as follows
$colors= array('red','blue','green','yellow');
foreach ($colors as $color){
//add your codes
}
?>
Example 2
$capitals= array("Ohio"=> "Columbus","Towa"=> "Des Moines","Arizona"=> "Phoenix");
foreach($capitals as $key=> $val){
//add your codes
}
while()
while() is usually used in conjunction with list() and each().
#example2:
The code is as follows
$colors = array('red','blue','green','yellow');
while(list($key,$val) = each($colors)) {
echo "Other list of $val.
";
}
?>
Display results:
Other list of red.
Other list of blue.
Other list of green.
Other list of yellow.
3. for()
#example3:
The code is as follows
$arr = array ("0" => "zero","1" => "one","2" => "two");
for ($i = 0;$i < count($arr); $i++) {
$str = $arr[$i];
echo "the number is $str.
";
}
?>
Display results:
the number is zero.
the number is one.
the number is two.
========= The following is the function introduction ==========
key()
mixed key(array input_array)
The key() function returns the key element in input_array at the current pointer position.
#example4
The code is as follows
$capitals = array("Ohio" => "Columbus","Towa" => "Des Moines","Arizona" => "Phoenix");
echo "
Can you name the capitals of these states?
";Can you name the capitals of these states?
Ohio
Towa
Arizona
each() function traverses the array
Example 1
The code is as follows
$people = array("Peter", "Joe", "Glenn", "Cleveland");
print_r (each($people));
?>
Output:
Array ( [1] => Peter [value] => Peter [0] => 0 [key] => 0 )
Son 2
each() is often used in conjunction with list() to iterate over an array. This example is similar to the previous example, but the entire array is output in a loop:
The code is as follows
Copy code
$people = array("Peter", "Joe", "Glenn", "Cleveland");
reset($people);
while (list($key, $val) = each($people))
{
echo "$key => $val
";
}
?>
Output:
0 => Peter
1 => Joe
2 => Glenn
3 => Cleveland
Recursive traversal of multidimensional arrays
The code is as follows
/*
*------------------------------------------------
*Author:
* Url : www.45it.com* Date : 2011-03-09
*------------------------------------------------
*/
function arr_foreach ($arr)
{
if (!is_array ($arr))
{
return false;
}
foreach ($arr as $key => $val )
{
if (is_array ($val))
{
arr_foreach ($val);
}
else
{
echo $val.'
';
}
}
}
$arr1 = array (1=>array(11,12,13,14=>array(141,142)),2,3,4,5);
echo '
';
print_r($arr1);
echo '';arr_foreach ($arr1);
?>Results
Array
(
[1] => Array
(
[0] => 11
[1] => 12
[2] => 13
[14] => Array
(
[0] => 141
[1] => 142
))
[2] => 2
[3] => 3
[4] => 4
[5] => 5
)
11
12
13
141
142
2
3
4
5