This article introduces the reference problem analysis and precautions in the php foreach loop. I hope this article will be helpful to you.
Example
| The Code is as follows: |
Copy code |
|
<? Php
$ Array = array ('A', 'B', 'C', 'D ');
Foreach ($ array as $ key => $ val ){
// Do something
}
Echo $ val; // Output d
Echo $ kay; // output 3
$ Val = 'E ';
Print_r ($ array); // output Array ([0] => a [1] => B [2] => c [3] => d)
?> |
In a foreach loop, $ key and $ val variables are not automatically released after the loop ends. The value is retained.
When foreach is referenced, the following situations may occur.
| The Code is as follows: |
Copy code |
|
<? Php
$ Array = array ('A', 'B', 'C', 'D ');
Foreach ($ array as $ key =>&$ val) {// use reference
// Do something
}
Echo $ val; // Output d
Echo $ kay; // output 3
$ Val = 'E ';
Print_r ($ array); // output Array ([0] => a [1] => B [2] => c [3] => e)
?> |
When the $ val variable is used and referenced, after the foreach loop is executed, $ val points to the same memory address as $ arrar [3.
After the foreach loop ends, the $ val variable still exists. Therefore, changing the value of $ val after the foreach loop ends is equivalent to changing the value of $ arrar [3.