1,foreach is the cyclic output of an array of PHP.
Example:
$arr = Array ("1" = "111", "2" = "222", "3" = "333"), and foreach ($arr as $key = = $value) { echo $key. = ". $value." \ n ";}
The results are as follows:
1=>1112=>2223=>333
2, make a slight change:
foreach ($arr as $key = + $value) {//echo $key. " = ". $value." \ n "; $key = & $arr [$key];} Print_r ($arr);
The results are as follows:
Array ( [1] = 2 [2] = 3 [3] = 333)
Code Explanation:
We found that the original array was modified, for what? Let's take a look at it.
The key points in the code are: $key = & $arr [$key];
$key is a reference to $arr [$key], that is, when $key is modified, $arr [$key] is also modified to the corresponding value.
First, let's look at the principle of foreach, which is to assign values to $key and $value, respectively;
So, $key, $value is also a common variable.
Then analysis, the first cycle, $key = & $arr [$key], meaning & $arr [1] point to the variable $key.
When the Foreach loop is repeated to the second pass, first, $key is assigned a value of 2, at which point, $key = & $arr [$key];
The result: $arr [1] is assigned a new $key at this time, that is, 2.
At the end of the second loop, the original array becomes:
Array ( [1] = 2 [2] = 222 [3] = 333)
Similarly, at the end of the third cycle, the following is:
Array ( [1] = 2 [2] = 3 [3] = 333)
By this, it is probably clear that.
3, in order to understand more clearly, the assignment process in foreach, we can do this:
$arr = Array ("1" = "111", "2" = "222", "3" = "333"), foreach ($arr as $key = = $value) {$key = & $arr [$key] ; $key = "Hello"; unset ($key);p rint_r ($arr);}
The results are as follows:
Array ( [1] = Hello [2] = 222 [3] = = 333) Array ( [1] = = Hello [2] = = Hello [ 3] =&G T 333) Array ( [1] = = Hello [2] = = Hello [3] = = Hello)
Code Explanation:
We assign the $key to "hello" directly in each loop, in order not to affect it, then release the $key variable.
This should be, it is more clear.