Introduction to program BUG caused by using foreach and reference in PHP. The copy code is as follows: $ aarray (); $ barray (); foreach ($ aas outputs 12 loops: the content of the element needs to be modified in the first loop.
The code is as follows:
$ A = array (1, 2 );
$ B = array (11, 12 );
Foreach ($ a as & $ r ){
}
Foreach ($ B as $ r ){
}
Echo $ a [1]; // output 12
The intention of the two loops may be: the first loop needs to modify the element content in the loop, so reference is used; but the second loop only treats $ r as a temporary variable. but why does the value of $ a [1] change?
After the iteration of $ a is complete, $ r is a reference of $ a [1]. changing the value of $ r is to change $ a [1]. in this case, you may wonder that $ r is not modified in the code or $ a [1?
In fact, foreach operates on copying arrays. Therefore, the next iteration is equivalent:
The code is as follows:
For ($ I = 0; $ I $ R = $ B [$ I]; // modified $ r! Equivalent to $ a [1] = $ B [$ I];
}
To avoid this situation, you should execute
The code is as follows:
Unset ($ r );
Delete the variable $ r from the current environment (reference variable ).
Even if it is not the previous example, after the first iteration, it is very likely that similar statements will be executed again:
The code is as follows:
$ R = 123;
Loop variables are usually temporary variables. the same variable name represents different things in different places of the code, but the scope of the variables exists outside the loop. this is the disadvantage of this scope rule. In addition, the "variable is used without declaration" is added, and the variable has no type.
Therefore, to use reference variables in PHP, you should unset () after the reference is used. all variables should be unset () before use ().
The http://www.bkjia.com/PHPjc/325872.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/325872.htmlTechArticle code is as follows: $ a = array (1, 2); $ B = array (11, 12 ); foreach ($ a as // the intention of outputting 12 loops may be: the first loop needs to modify the element content in the loop...