The foreach statement is used to traverse the array. each time an array is cyclically traversed, the value of the current array element is assigned to the value variable (the array pointer is moved one by one). The syntax is as follows:
The foreach statement is used to traverse the array cyclically. The value of the current array element is assigned to the value variable (the array pointer is moved one by one). The syntax is as follows:
- Foreach (array as value)
- {
- Code to be executed;
- }
The following example demonstrates a loop that outputs the value of a given array:
-
-
- $ Arr = array ("one", "two", "three ");
- Foreach ($ arr as $ value)
- {
- Echo "value:". $ value ." ";
- }
- ?>
-
-
The following describes in detail:
- Foreach ($ array as & $ row ){
- $ Row = explode ('/', $ row );
- }
- Foreach ($ array as $ row ){
- // Do something
- }
In this case, a logic error occurs in the second loop. in the second loop, do something outputs $ row, and the output at the end of the loop is the second-to-last element, instead of the last one, write as follows:
- Foreach ($ array as & $ row ){
- $ Row = explode ('/', $ row );
- }
- Unset ($ row );
- Foreach ($ array as $ row ){
- // Do something
- }
Or write the code in the first loop as follows:
- Foreach ($ array as $ key => $ row ){
- $ Array [$ key] = explode ('/', $ row );
- }