: This article mainly introduces PHPforeach usage and examples. if you are interested in PHP tutorials, refer to it. Original website:
Http://blog.csdn.net/china_skag/article/details/6444727
PHP 4 introduces the foreach structure, which is similar to Perl and other languages. This is just a simple way to traverse arrays. Foreach can only be used for arrays. an error occurs when you try to use it for another data type or an uninitialized variable. There are two types of syntax. The second type is secondary, but it is the first type of useful extension.
Foreach (array_expression as $ value)
Statement
Foreach (array_expression as $ key => $ value)
Statement
The first format traverses the given array_expression array. In each loop, the value of the current unit is assigned to $ value and the pointer inside the array moves forward (so the next unit will be obtained in the next loop ).
The second format does the same thing, except that the key name of the current unit is assigned to the variable $ key in each loop.
First, let's look at the first statement. this statement is relatively simple. array_expression refers to an array expression. the as $ val statement obtains the values of this array in sequence and saves them to the $ val variable, in this method, only values in the array can be obtained, but the subscript index value of the array cannot be obtained. For example:
$ MyArray = array ("1" => "val1", "2" => "val2", "3" => "val3 ");
Foreach ($ myArray as $ val ){
Print ($ val ."");
}
The result will be output: val1 val2 val3
Let's take a look at the second format. in addition to getting the values of elements in the array, the second format can also get the index values of elements and save them to the $ key variable, if the index value of the array is not manually set, the default value is returned,
Look at the positive example:
Let's first look at a simple one-dimensional array:
$ MyArray = array ("1" => "val1", "2" = "val2", "3" => "val3 ");
Foreach ($ myArray as $ key => $ val ){
Print ($ key. "=>". $ val .";");
}
The program will output: 1 => val1; 2 => val2; 3 => val3;. Next let's look at a complex two-dimensional array traversal. The program is as follows:
$ MyArray = array (
"1" => array ("11" => "val11", "12" => "val12", "13" => "val13 "),
"2" => array ("21" => "val21", "22" => "val22", "23" => "val23 "),
"3" => array ("31" => "val31", "32" => "val32", "33" => "val33 ")
);
Print ("
");
Foreach ($ myArray as $ key => $ val ){
Print ("
- ". $ Key ."
");
If (is_array ($ val) {// checks whether the $ val value is an array. if yes, it goes to the lower-layer traversal.
Print ("
");
Foreach ($ val as $ key => $ val ){
Print ("
- ". $ Key." => ". $ val ."
");
}
Print ("
");
}
}
Print ("
");
Output result:
1
11 => val11
12 => val12
13 => val13
2
21 => val21
22 => val22
23 => val23
3
31 => val31
32 => val32
33 => val33