foreach It is easy to modify the elements of the array by adding & before $value, such as:
PHP代码
|
But this usage is also easy to cause errors, and it is not easy to find.
Look at the example to make it more straightforward:
PHP代码
|
Let’s see if the output result is the same as expected. The result here is:
a4
b4
b4
The result is different from what I expected. This is a problem caused by quotation.
When foreach($arr as &$value) traverses the array to the end, the reference relationship is not broken. This is equivalent to the reference of the last unit of $value and $arr, which is $arr[2].
Going to foreach($arr2 as $value), the value of $value always changes with the value of the array unit. Since the reference relationship is not broken, the value of $arr[2] also changes accordingly. Until $arr2 is traversed, the value of $value is f, so the value of $arr[2] is also f.
At this time, the value of $arr should be:
Array
(
[0] => a4
[1] => b4
[2] = > f
)
This is different from the final output we see. Then go to foreach($arr as $value). In the same way, the value of $arr[2] also changes with $value. When the key is 1, that is, $arr[1], $arr[2] The value also becomes the value of $arr[1], which is b4. Then when the key is 2, the value of $arr[2] becomes the value of $arr[2], which is b4. It is the result of output.
So be careful when using references in foreach. You can also disconnect the reference relationship immediately after processing, so that the above situation will not happen later.
PHP代码
|