PHP foreach concerning the use of variable references pit

PHP version 5.6.12 code is as follows:

 
1
2
3
4
5
6
7
8
9
10
11
12
<?php
$arr = [ 'a' , 'b' , 'c' , 'd' , 'e' ];
foreach ( $arr as $i =>& $a ) {
   $a = $a . '_' . $a ;
   echo $a . '<br>' ;
}
echo '<hr>' ;
foreach ( $arr as $i => $a ) {
   echo $a . '<br>' ;
}
echo '<hr>' ;
print_r( $arr );

Output

Beginning to see the results of the second output foreach feeling very strange, how can output two d_d it?

Careful thought, the original because the PHP foreach $ a local variable scope is the entire function is still valid in the outer loop, rather than being enclosed within the loop,

So when $ a is not new variables when performing the second foreach, but still point to $ arr array address 5th element of reference,

When the second foreach actually stop to the 5th element array $ arr assignment in the cycle,

Specific assignment situation,

First: a_a assigned to the fifth element, the result is: [a_a, b_b, c_c, d_d, a_a]

Second: b_b assigned to the fifth element, the result is: [a_a, b_b, c_c, d_d, b_b]

Third: c_c assigned to the fifth element, the result is: [a_a, b_b, c_c, d_d, c_c]

Fourth: d_d assigned to the 5th element, the result is: [a_a, b_b, c_c, d_d, d_d]

Fifth: At this time, since the fifth element has become d_d again to d_d assigned to the 5th element, the result was to: [a_a, b_b, c_c, d_d, d_d]

Solution:

1. try not to use the same variable name loop;

2. After each use or use again unset ($ a) supra; treatment, release application address

foreach ($arr as $i=>&$a) {

   $a = $a . '_' . $a ;
   echo $a . '<br>' ;
}
echo '<hr>' ;
echo $a ;
echo '<hr>' ;
 
// 这里 unset 掉
unset( $a );
 
echo $a = 'ccc' ;
echo '<hr>' ;
print_r( $arr );
echo '<hr>' ;
foreach ( $arr as $i => $a ) {
   echo $a . '<br>' ;
}
echo '<hr>' ;
print_r( $arr );

Output:

Now normal

Guess you like

Origin www.cnblogs.com/niuben/p/12193311.html