This section describes a special looping statement in PHP, the "foreach" loop statement.
What is a foreach loop for?
In PHP, the Foreach Loop statement, which is designed to iterate through an array, can be viewed in this article http://www.php.cn/php-weizijiaocheng-360217.html
foreach Loop syntax format
The Foreach Loop syntax is written in two ways, and the first one is as follows
foreach (Array_variable as Val) statement;
Array_variable represents an array variable, and every time the loop executes, the value of each element is temporarily assigned to the variable val,statement the value of Val is different each time it gets
The second type of notation
foreach (array_variable as key = val) statement;
The key represents the subscript of the array, and Val represents the value of the array, so for a numeric subscript array, the value of key in each loop is the number that grows from 0 onwards.
foreach Loop instance
<?phpheader ("Content-type:text/html;charset=utf-8"); Set the encoding $a=array ("Apple", "orange", "banana"), foreach ($a as $value) { echo $value. <br/> ";}? >
Code Run Result:
Detailed Examples:
We said at the beginning that the "foreach" loop is dedicated to looping the array, so we first define an array of $ A, in which there are three values, namely "Apple", "orange", "banana", and then iterate through the array using the Foreach Loop statement, and the values in the output array.
The above example is the first way to use the Foreach Loop, at which point, if you want to get the $key of the array, use our second notation, the code is as follows:
<?phpheader ("Content-type:text/html;charset=utf-8"); Set the encoding $ A = Array ("one" + = 1, "one" + = 2, "three" = 3, "Seventeen" = +); foreach ($a as $key = = $val) { echo $key. ":". $val. " <br/> ";}? >
Code Run Result:
The above two examples are the simple application of the Foreach Loop two kinds of notation.