foreach can easily modify an array of cells by adding & before $value, such as:
PHP code
- foreach($arr as &$value) {
- $value . = ' 4 ';
- }
|
But this usage is also easy to make mistakes, and it is not easy to find.
See the example more straightforward:
PHP Code
- <?php
- $arr = array(' A ',' B ', 'C ');
- $arr 2 = array(' d ', ' e ', ' f ');
- foreach($arr as &$value) {//accustomed to using $value or $val
- $value . = ' 4 ';
- }
- We have finished processing in the page template output, first output $arr2
- foreach($arr 2 as $value) {//accustomed to using $value or $val
- //echo $value;
- }
- And then output $arr like this;
- foreach($arr as $value) {//accustomed to using $value or $val
- echo $value, "n";
- }
- ?>
|
Let's see if the output turns out to be the same as expected. Here the result is:
A4
B4
B4
The result is different from what I expected, and this is the problem that the citation causes.
At the end of a foreach ($arr as & $value) array, the reference relationship is not disconnected, which is equivalent to the last unit of the $value and $arr that is $arr [2] reference.
To foreach ($arr 2 as $value), the value of the $value has been changed with the value of the array cell, and the value of $arr [2] changes as the reference relationship is not broken. All the time until the $ARR2 traversal, this is the $value value is F, so $arr[2] value is also f.
Then the value of $arr should be:
Array
(
[0] => A4
[1] => B4
[2] => F
)
This is not the same as the final output we see. Again to foreach ($arr as $value), the value of $arr [2] also 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. Then the value of the key 2 o'clock $arr [2] becomes the value of the $arr [2], which is B4. Is the result of the output.
So be aware when foreach uses the reference. You can also disconnect the referral relationship as soon as you have finished processing it.
php code
- foreach ( $arr as &< Span class= "VARs" $value ) {
- $value .= ' 4 ' /span>
-
- unset ( $value );
|