Foreach loop instance usage
In PHP, foreach is used to loop all elements of an array. The basic foreach syntax of the author is as follows:
The code is as follows: |
Copy code |
FOREACH ($ array_variable as $ value) { [Code to execute] } Or FOREACH ($ array_variable as $ key => $ value) { [Code to execute] } |
In these two cases, multiple [code executions] will be executed equal to the number of elements in the $ array_variable array.
Let's look at an example. Suppose we have the following code segment:
The code is as follows: |
Copy code |
$ Array1 = array (1, 2, 3, 4, 5 ); FOREACH ($ array1 as $ abc) { Print "new value is". $ abc * 10. "<br> "; } |
Output result
The code is as follows: |
Copy code |
New value is 10 New value is 20 New value is 30 New value is 40 New value is 50 |
The above is the method we often use for foreach, and we will look at the example below
The code is as follows: |
Copy code |
$ A = array (1, 2 ); $ B = array (11, 12 ); Foreach ($ a as & $ r ){ } Foreach ($ B as $ r ){ } Echo $ a [1]; // output 12 |
The intention of the two loops may be: the first loop needs to modify the element content in the loop, so reference is used; but the second loop only treats $ r as a temporary variable. but why does the value of $ a [1] change?
After the iteration of $ a is complete, $ r is a reference of $ a [1]. Changing the value of $ r is to change $ a [1]. in this case, you may wonder that $ r is not modified in the code or $ a [1?
In fact, foreach operates on copying arrays. Therefore, the next iteration is equivalent:
The code is as follows: |
Copy code |
For ($ I = 0; $ I <count ($ B); $ I ++ ){ $ R = $ B [$ I]; // modified $ r! Equivalent to $ a [1] = $ B [$ I]; } |
To avoid this situation, you should execute
The code is as follows: |
Copy code |
Unset ($ r ); |
Delete the variable $ r from the current environment (reference variable ).
Even if it is not the previous example, after the first iteration, it is very likely that similar statements will be executed again:
The code is as follows: |
Copy code |
$ R = 123; |
Loop variables are usually temporary variables. The same variable name represents different things in different places of the code, but the scope of the variables exists outside the loop. this is the disadvantage of this scope rule. In addition, the "variable is used without declaration" is added, and the variable has no type.
Therefore, to use reference variables in PHP, you should unset () after the reference is used. All variables should be unset () before use ().
Summary:
PHP references some pointers similar to the C language, but some important features are different from the C language pointers. If you do not pay attention to them, it will lead to a program BUG. foreach operates on copying an array or object, but PHP5 can use the reference operation to operate the object element itself.