foreach can easily modify the cells of an array by adding & before the $value, such as:
PHP code
Copy the Code code as follows:
foreach ($arr as $value) {
$value. = ' 4 ';
}
But this usage is also very easy to make mistakes, and it is not easy to find.
See examples more straightforward:
PHP code
Copy the Code code as follows:
$arr = Array (' A ', ' B ', ' C ');
$arr 2 = Array (' d ', ' e ', ' f ');
foreach ($arr as $value) {//used with $value or $val
$value. = ' 4 ';
}
We're finished with the page template output, first output $arr2
foreach ($arr 2 as $value) {//used with $value or $val
Echo $value;
}
Then output $arr like this;
foreach ($arr as $value) {//used with $value or $val
echo $value, "\ n";
}
?>
Let's see if the output is the same as expected. Here's the result:
Copy the Code code as follows:
xml/html Code
A4
B4
B4
The result is not the same as I expected, this is the problem that the citation causes.
In the foreach ($arr as & $value) array traversal to the end, the reference relationship is not broken, which is equivalent to the $value with the last cell of the $arr that is $arr [2] reference.
To foreach ($arr 2 as $value), the value of the $value is always changed with the value of the array cell, and the value of $arr [2] changes as the reference relationship is not broken. Until $ARR2 is finished, this is the $value value is F, so $arr[2] value is also f.
At this point the value of $arr should be:
xml/html Code
Copy the Code code as follows:
Array
(
[0] = A4
[1] = B4
[2] = f
)
This is not the same as the final output we saw. Then to the foreach ($arr as $value), the same is true when the value of $arr [2] changes with $value, and when traversing to key 1, or $arr[1], the value of $arr [2] becomes the value of $arr [1], which is B4. And then traversing to key 2 o'clock $arr [2] is the value of $arr [2], which is B4. Is the result of the output.
So be careful when using a reference in foreach. You can also disconnect the reference relationship immediately after processing, and there will be no such situation behind.
PHP code
Copy the Code code as follows:
foreach ($arr as $value) {
$value. = ' 4 ';
}
Unset ($value);
The above describes the outdoor of PHP foreach use & and Operator reference assignment to pay attention to the issues, including the outdoor of the content of the field, I hope that the PHP tutorial interested in a friend helpful.