1, foreach is the loop output of php on the array.
Example:
$arr = array("1"=>"111","2"=>"222","3"=>"333"); foreach($arr as $key=>$value) { echo $key."=>".$value."\n"; }
The result is as follows:
1=>111 2=>222 3=>333
2, slightly modified:
foreach($arr as $key=>$value) { //echo $key."=>".$value."\n"; $key = &$arr[$key]; } print_r($arr);
The result is as follows:
Array ( [1] => 2 [2] => 3 [3] => 333 )
Code explanation :
We found that the original array was modified. Why? Let's study it.
The key part in the code is: $key = &$arr[$key];
$key is the reference of $arr[$key], that is , when $key is modified, $arr[$key] is also modified to the corresponding value.
First of all, we need to understand the principle of foreach. It assigns the values of the array to $key and $value respectively;
So, $key and $value are also ordinary ones. variable.
Next analysis, in the first loop, $key = &$arr[$key]; means &$arr[1] points to the variable $key.
When the foreach loop reaches the second pass, first, $key is assigned a value of 2. At this time, pay attention again, $key = &$arr[$key];
The result is :$arr[1] is assigned the new $key at this time, which is 2.
After the second loop ends, the original array becomes:
Array ( [1] => 2 [2] => 222 [3] => 333 )
Similarly, After the third cycle ends, it will be:
Array ( [1] => 2 [2] => 3 [3] => 333 )
At this point, it has been roughly explained.
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); print_r($arr); }
The result is as follows:
Array ( [1] => hello [2] => 222 [3] => 333 ) Array ( [1] => hello [2] => hello [3] => 333 ) Array ( [1] => hello [2] => hello [3] => hello )
Code explanation:
We directly assign the value "hello" to $key in each loop, so as not to affect it, and then release the $key variable.
This should make it clearer.
The above is the detailed content of Analysis of problems arising from foreach reference in php. For more information, please follow other related articles on the PHP Chinese website!