The following is a simple PHP pen exam (Advanced required). If you want to go to the interview, please refer to this pen exam. The following is a simple PHP pen exam (Advanced required). If you want to go to the interview, please refer to this pen exam.
Script ec (2); script
Once, a senior gave me a PHP written test. The questions are roughly as follows:
The Code is as follows: |
|
$ Arr = array ('1', '2', '3 '); Foreach ($ arr as $ key =>&$ val ){} Foreach ($ arr as $ key => $ val ){} Var_dump ($ arr ); |
What is the answer?
After reading it, I will be ready? I don't know where the question is. The difference between the two foreach statements is that one is the address and the other is not the address. Will this affect the result?
The output result is
The Code is as follows: |
|
Array ( 0 => string '1' (length = 1) 1 => string '2' (length = 1) 2 => & string '2' (length = 1) ) |
Why is the printed data like this? Where did "3" go?
The reason for this is: & the address is correct.
In this way, it is intuitive to use foreach to read arrays.
Then, the loop is the moving reading of the pointer, and because it is an & value, the address is read directly, but the assignment is not simple. So when the first loop ends. $ Val and $ arr [2] refer to the same address. Therefore, if the $ val value is changed, the value of $ arr ['2'] also changes.
If you run the following code:
The Code is as follows: |
|
$ Arr = array ('1', '2', '3 '); Foreach ($ arr as $ key =>&$ val ){} Foreach ($ arr as $ key => $ val ){ Var_dump ($ arr ); } Var_dump ($ arr ); |
You can see the change process. And the reason for obtaining the previous results