Talking about the pitfall of using referenced variables for foreach in PHP
I have been writing PHP for many years, but still make low-level mistakes. Today I am faced with a hole in referencing variables in foreach. The PHP version is 5.6.12 and the code is as follows:
<?php$arr = ['a', 'b', 'c', 'd', 'e'];foreach ($arr as $i=>&$a) { $a = $a.'_'. $a; echo $a .'<br>';}echo '
Output result
The result of the second foreach output at the beginning is very inexplicable. How can we output two d_d statements?
I thought about it carefully. Because the $ a scope in PHP foreach is the local variable of the entire function, it is still valid outside the loop, rather than being closed in the loop,
Therefore, when executing the second foreach, $ a is not a new variable, but still pointing to the address reference of the 5th elements in the $ arr array,
When the second foreach is in a loop, it is actually constantly assigning values to the 5th elements of the $ arr array,
Specific assignment information,
The first time: a_a is assigned to 5th elements. The result is [a_a, B _ B, c_c, d_d, a_a].
The second time: B _ B is assigned to 5th elements. The result is [a_a, B _ B, c_c, d_d, B _ B].
The third time: c_c is assigned to 5th elements. The result is [a_a, B _ B, c_c, d_d, c_c].
The fourth time: d_d is assigned to 5th elements. The result is [a_a, B _ B, c_c, d_d, d_d].
Fifth time: at this time, because the fifth element has changed to d_d, the value of d_d is assigned to 5th elements again. The result is [a_a, B _ B, c_c, d_d, d_d].
Solution:
1. Try not to use the same loop variable name;
2. unset ($ a) before each use or reuse; Process and remove the address application
Use the code example above:
$ Arr = ['A', 'B', 'C', 'D', 'E']; foreach ($ arr as $ I =>& $) {$ a = $. '_'. $ a; echo $. '<br>';} echo '
Output result:
Now it's normal. Pay attention to these small details.
The above is a small Editor for you to talk about all the content in PHP about the use of variables to reference foreach. I hope you can support more help ~