<?PHP$arr=Array(' A ', ' B ', ' C ');foreach($arr as&$v) {}foreach($arr as $v) {}Var_dump($arr);/*The result is: Array (3) {[0]=> string (1) "A" [1]=> string (1) "B" [2]=> &string (1) "B"}*///The first foreach assigns the value of the array to $v in the same way as a reference assignment. $arr=Array(' A ', ' B ', ' C ');foreach($arr as&$v) {}Var_dump($v);//at this point, the value of $v is C, which is the reference assignment, $v points to the address space of the string C. The second foreach assigns the values of the array to the $v in the same way as the copy assignment. Since the current $v points to the address space of C, changing the value of $v changes the value of the address space occupied by C. $arr=Array(' A ', ' B ', ' C ');foreach($arr as&$v) {}foreach($arr as $v) { Var_dump($arr); Break;}//The first assignment assigns a value of a to $v, and the value of the address space of the original C becomes a, when the array (' A ', ' B ', ' a '). And so the first assignment c->a, the second assignment is a->b, the third assignment is b->b,//so the final result is an array (' A ', ' B ', ' B ').
The problem is that the foreach itself is an assignment process, when the first foreach ends $value and $arr[2] Two variables point to $arr[2], and the second time when foreach is essentially an assignment behavior, that is, $ Value = $arr [0; This makes $arr[2] the same as the second time $arr[2] = $arr [1] causes $arr [2] Each cycle will be re-assigned value
Bug caused by the PHP array foreach reference