A "pit" in PHP, PHP "pit"
To say a very likely problem encountered at work--foreach reference
$arr Range (1,3); // [A] foreach ($arr as &$val) {} foreach ($arras$val) {} Print_r ($arr
Above this code output what, magical unexpectedly is the following, this I met once in the work, at that time did not make a day, but found a solution, this problem solution has two:
Array ( [0] = 1 [1] = 2 [2] = 2)
Both of the following methods can solve the problem above:
// Method 1 foreach ( $arr as & $value ) {} unset ( $value ); foreach ( $arr as $value ) {} Print_r ( $arr ); // [1,2,3]//Method 2 foreach ( $arr as & $value ) {} foreach ( $arr as $val ) {} Print_r ( $arr ); // [1,2,3]//Method 3 foreach ( $arr as & $value ) {} foreach ( $arr as & $value ) {} Print_r ( $arr ); // [I/a]
Method 1 in the official manual can also see http://php.net/manual/en/control-structures.foreach.php, the article has a tips tip this $var = 123; $tmp = &$var; $tmp = $; Echo $var ; // $
Look at this stolen picture below (haha, the original link is posted below), on the above this better understanding
PHP$arr 1 = array("a" = 1, "b" = 2, "c" = 3); $arr 2 = array("x" = 4, "Y" = 5, "z" = 6); foreach ($arr 1 as $key = &$val) {} foreach ($arr 2 as $key = + $val) {} Var_dump ($arr 1); Var_dump ($arr 2);? > Theoutputis: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 belongs to the author Iforever (luluyrt@163.com) all, without the author's consent to prohibit any form of reprint, reprinted article must be in the article page obvious location to the author and the original text connection, otherwise reserve the right to pursue legal responsibility.
http://www.bkjia.com/PHPjc/975062.html www.bkjia.com true http://www.bkjia.com/PHPjc/975062.html techarticle a "pit" in PHP, PHP "pit" says a very likely problem encountered at work foreach reference $arr = range (1,3);//[All-in-one] foreach ($arr as $val) {} foreach ($ar R as $ ...