Write PHP for many years, but still make a low-level error, today encountered a foreach reference variable when the pit, PHP version of the 5.6.12 code is as follows:
<?php
$arr = [' A ', ' B ', ' C ', ' d ', ' e '];
foreach ($arr as $i =>& $a) {
$a = $a. ' _ '. $a;
echo $a. ' <br> ';
}
Echo '
Output results
First saw the result of the second foreach output is very puzzling, how can output two d_d?
Think about it, because the $a scope of PHP foreach is a local variable of the entire function, which is still valid outside the loop, rather than being enclosed within the loop,
So when the second foreach is executed, the $a is not a new variable, but it still points to an address reference to the 5th element of the $arr array.
When the second foreach is in the loop, it is actually giving a value to the 5th element of the $arr array,
Specific assignment,
First time: A_a assignment to the 5th element, the result is: [A_a, B_b, C_c, D_d,a_a]
Second time: B_b assignment to the 5th element, the result is: [A_a, B_b, C_c, D_d,b_b]
Third time: C_c assignment to the 5th element, the result is: [A_a, B_b, C_c, D_d,c_c]
Fourth time: D_d assigned to the 5th element, the result is: [A_a, B_b, C_c, D_d,d_d]
Fifth time: Now because the Fifth element has become d_d and D_d assigned to the 5th element, the result is: [A_a, B_b, C_c, D_d,d_d]
Solution:
1. Try not to use the same cycle variable name;
2. unset ($a) before the end of each use or reuse; handling, removing address application
Or use the code example above:
$arr = [' A ', ' B ', ' C ', ' d ', ' e '];
foreach ($arr as $i =>& $a) {
$a = $a. ' _ '. $a;
echo $a. ' <br> ';
}
Echo '
Output results:
It's normal now, and these little details must be noticed.
The above is a small series for everyone to talk about the use of the reference variable in PHP, all the contents of the pit, I hope that we support the cloud-Habitat Community ~