An odd piece of PHP code

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.