In PHP, the foreach loop statement is used to traverse arrays cyclically. This chapter introduces a special loop statement in PHP, "foreach" loop statement.
What is foreach loop used?
Bytes
Foreach loop syntax format
The foreach loop syntax can be written in either of the following ways:
foreach (array_variable as val) statement;
Array_variable represents an array variable. during each loop execution, the values of each element are temporarily assigned to the variable val. the values of the val obtained by each statement are different.
Method 2
foreach (array_variable as key => val) statement;
Key indicates the subscript of the array, and val indicates the value of the array. for the number subscript array, the key value in each loop is a number that grows from 0.
Foreach loop instance
";}?>
Code running result:
The above example is the first way to use the foreach loop. in this case, if you want to get the $ key of the array, you need to use our second method. the code is as follows:
1, "two" => 2, "three" => 3, "seventeen" => 17); foreach ($ a as $ key => $ val) {echo $ key. ":". $ val."
";}?>
Code running result:
The two examples above are simple application of the foreach loop statements.
The above is a detailed description of the "foreach" loop statement instance in PHP loop control statements. For more information, see other related articles in the first PHP community!