A "pitfall" in PHP and a "pitfall" in PHP ". A "pitfall" in PHP, the PHP pitfall says a foreach reference to a very likely problem at work $ arrrange (); [, 3] foreach ($ arras $ val) {} foreach ($ arras $ A "pitfall" in PHP, "pitfall" in PHP"
A problem that is very likely to be encountered at work -- reference of foreach
$arr = range(1,3);//[1,2,3]foreach($arr as &$val) {}foreach($arr as $val) {}print_r($arr);
What is the output of the above code? what's amazing is the following: I met this once at work. I didn't come up with a solution after a long time, but I found a solution, there are two solutions to this problem:
Array( [0] => 1 [1] => 2 [2] => 2)
Both of the following methods can solve the above problem:
// Method 1 foreach ($ arr as & $ value) {} unset ($ value); foreach ($ arr as $ value) {} print_r ($ arr ); // [, 3] // method 2 foreach ($ arr as & $ value) {} foreach ($ arr as $ val) {} print_r ($ arr ); // [, 3] // method 3 foreach ($ arr as & $ value) {} print_r ($ arr ); // [1, 2, 3]
Method 1 you can also see http://php.net/manual/en/control-structures.foreach.php in the official manual. in this document, a dedicated tipsprompts that the response callback var = 123; $ tmp = & $ var; $ tmp = 200; echo $ var; // 200
Take a look at the stolen figure below (haha, the original article link is posted below) to better understand the above
1, "B" => 2, "c" => 3); $ arr2 = array ("x" => 4, "y" => 5, "z" => 6); foreach ($ arr1 as $ key => & $ val) {} foreach ($ arr2 as $ key => $ val) {} var_dump ($ arr1); var_dump ($ arr2);?> The output is: array (3) {["a"] => int (1) ["B"] => int (2) ["c"] => & int (6)} array (3) {["x"] => int (4) ["y"] => int (5) ["z"] => int (6 )}
References:
Http://www.cnblogs.com/CraryPrimitiveMan/p/4030748.html#3085766
Http://www.jb51.net/article/39299.htm
The copyright of this article is owned by the author iforever (luluyrt@163.com), without the author's consent to prohibit any form of Reprint, repost the article must be in the obvious position on the article page to give the author and the original connection, otherwise, you are entitled to pursue legal liability.
When "pitfall" says a problem that is very likely to be encountered at work foreach references $ arr = range (1, 3); // [1, 2, 3] foreach ($ arr as $ val) {} foreach ($ arr as $...