Foreach can easily modify the array unit by adding & before $ value, but this usage is also easy to cause errors and cannot be easily found.
Foreach can easily modify the array unit by adding & before $ value, such:
PHP code
- Foreach ($ arr as & $ value ){
- $ Value. = '4 ';
- }
|
However, this method can easily cause errors and cannot be found.
The example is more straightforward:
PHP code
-
- $ Arr = array ('A', 'B', 'C ');
- $ Arr2 = array ('D', 'e', 'F ');
- Foreach ($ arr as & $ value) {// $ value or $ val
- $ Value. = '4 ';
- }
- // After processing is complete, we output the template on the page. First, we Output $ arr2.
- Foreach ($ arr2 as $ value) {// $ value or $ val
- // Echo $ value;
- }
- // Then output $ arr;
- Foreach ($ arr as $ value) {// $ value or $ val
- Echo $ value, "\ n ";
- }
- ?>
|
Check whether the output result is the same as expected. The result is:
A4
B4
B4
The result is different from what I expected. this is a problem caused by reference.
When the foreach ($ arr as & $ value) array is traversed to the end, the reference relationship is not broken, this is equivalent to the last unit of $ value and $ arr, that is, $ arr [2] reference.
Then to foreach ($ arr2 as $ value), the value of $ value always changes with the value of the array unit. because the reference relationship is not broken, the value of $ arr [2] also changes. After traversing $ arr2, the value of $ value is f, so the value of $ arr [2] is also f.
The value of $ arr should be:
Array
(
[0] => a4
[1] => b4
[2] => f
)
This is different from the final output. Then to foreach ($ arr as $ value), similarly, the value of $ arr [2] also changes with $ value. when the traversal key is 1, that is, when $ arr [1], the value of $ arr [2] is also changed to the value of $ arr [1], that is, b4. Then, when the key is 2, the value of $ arr [2] becomes the value of $ arr [2], that is, b4. Is the output result.
Therefore, you should pay attention to it when using foreach reference. You can also disconnect the reference relationship immediately after processing, and the above will not happen in the future.
PHP code
- Foreach ($ arr as & $ value ){
- $ Value. = '4 ';
- }
- Unset ($ value );
|