Home > Article > Backend Development > A 'pit' in PHP, PHP 'pit'_PHP Tutorial
Let's talk about a problem that is very likely to be encountered at work - a reference to foreach
<span>$arr</span> = <span>range</span>(1,3<span>); </span><span>//</span><span>[1,2,3]</span> <span>foreach</span>(<span>$arr</span> <span>as</span> &<span>$val</span><span>) { } </span><span>foreach</span>(<span>$arr</span> <span>as</span> <span>$val</span><span>) { } </span><span>print_r</span>(<span>$arr</span><span>); </span>
What does the above code output? The amazing thing is as follows. I encountered this once at work. It took me a long time to figure out the reason, but I just found a solution. There are two ways to solve this problem. Number:
<span>Array</span><span> ( [</span>0] => 1<span> [</span>1] => 2<span> [</span>2] => 2<span> )</span>
The following two methods can solve the above problem:
<span>//</span><span>方法1</span> <span>foreach</span> (<span>$arr</span> <span>as</span> &<span>$value</span><span>) { } </span><span>unset</span>(<span>$value</span><span>); </span><span>foreach</span> (<span>$arr</span> <span>as</span> <span>$value</span><span>) { } </span><span>print_r</span>(<span>$arr</span><span>); </span><span>//</span><span>[1,2,3] //方法2</span> <span>foreach</span> (<span>$arr</span> <span>as</span> &<span>$value</span><span>) { } </span><span>foreach</span> (<span>$arr</span> <span>as</span> <span>$val</span><span>) { } </span><span>print_r</span>(<span>$arr</span><span>); </span><span>//</span><span>[1,2,3] //方法3</span> <span>foreach</span> (<span>$arr</span> <span>as</span> &<span>$value</span><span>) { } </span><span>foreach</span> (<span>$arr</span> <span>as</span> &<span>$value</span><span>) { } </span><span>print_r</span>(<span>$arr</span><span>); </span><span>//</span><span>[1,2,3]</span>
Method 1 can also be seen in the official manual http://php.net/manual/en/control-structures.foreach.php. There is a special tip in the article to remind this $ var = 123; $tmp = &$var; $tmp = 200; echo $var; //200
Take a look at the stolen picture below (haha, the original link is posted below) to have a better understanding of the above
8874306e90966e7de1b8899554838cae 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) }
Reference article:
http://www.cnblogs.com/CraryPrimitiveMan/p/4030748.html#3085766
http://www.jb51.net/article/39299.htm
The copyright of this article belongs to the author iforever (luluyrt@163.com). Any form of reprinting is prohibited without the author’s consent. After reprinting the article, the author and the original text link must be given in an obvious position on the article page. Otherwise, we reserve the right to pursue legal liability.