The code for a strange PHP code is as follows: & lt ;? Php $ data = array ('A', 'B', 'C'); foreach ($ dataas $ key = & gt; $ val) {$ val = & amp; $ data [$ key]; a strange PHP code
The code is as follows:
$val) { $val = &$data[$key];}
Question 1: When the program is executed, what is the value of the variable $ data after each loop ends? Please explain.
Question 2: After the program is executed, what is the value of the variable $ data? Please explain.
Answer:
The complete expression of the array $ data described in this article is as follows:
$ Data = array (
0 => 'A', // memory space
1 => 'B', // memory space B
2 => 'C', // memory space c
);
Loop process:
$ Key = 0; $ val = 'a'; // $ val copies the value of the variable $ data [0. This assignment causes the variable $ val to be created and points to a new memory space X; $ val and $ data [0] point to different memory spaces.
$ Val = & $ data [0]; // $ val becomes a reference and points directly to the variable $ data [0] (the first unit of the original array ). $ Val and $ data [0] point to the same memory space.
$ Key = 1; $ val = 'B'; // The value assignment operation changes the value of the memory space pointed to by $ val; $ data [0] points to the same memory space, so the value of $ data [0] also changes.
$ Val = & $ data [1]; // $ val is a reference, but now it points to the variable $ data [1] (the second unit of the original array ). $ Val and $ data [1] point to the same memory space B.
$ Key = 2; $ val = 'C'; // The value assignment operation changes the value of the memory space pointed to by $ val; $ data [1] points to the same memory space, so the value of $ data [1] also changes.
$ Val = & $ data [2]; // $ val is a reference, but now it points to the variable $ data [2] (the third unit of the original array ). $ Val and $ data [2] point to the same memory space C.
For more information, see the PHP.net website's instructions in the following chapters: array, foreach, and reference.