Php reference foreach output problems

Source: Internet
Author: User
{Code...} output {code...}. Who will explain it?

  

Output

string(1) "1"string(1) "1"

Who will explain it?

Reply content:

   

Output

string(1) "1"string(1) "1"

Who will explain it?

Let's explain this.foreachExpand to assign values

foreach($arr as &$value) {    //noop}

Roughly

php#begin first foreach$value = &$arr[0];//noop$value = &$arr[1];//noop#end foreach

At this time, if you print $ arr, you will see

array(2) {  [0]=>  string(1) "1"  [1]=>  &string(1) "2"}

That is to say$valueStill yes$arr[1](Alias)

Then we split the second foreach.

php# Begin second foreach $ value = $ arr [0]; // note: Due to $ value <=> & $ arr [1], $ arr [1] is assigned $ arr [0], that is, 1var_dump ($ value); // 1 $ value = $ arr [1]; // equivalent to $ arr [1] = $ arr [1]; no actual effect var_dump ($ value); // 1 # end foreach

The solution is never used &

Or use unset to release the reference according to instructions on the official website.


    

$ Value and $ arr [1] point to the same memory space. The second loop actually changes the value of $ arr [1] for each loop.

After learning, let's simply look at the above answer.
After the first foreach ends, $ value = & $ arr [1]. Note that this is a reference, which can be understood as a pointer.
Focus on the second foreach:
The first time is & $ arr [1] = $ arr [0]. This isAssignment operationAt this time, $ arr [1]The value has been modified.It is $ arr [0], that is, 1. Now $ arr = ['0' => 1, '1' => 1].
The second time & $ arr [1] = $ arr [1], same as above. Final $ arr = ['0' => 1, '1' => 1].

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.