Notes for using references in the foreach loop in PHP

Source: Internet
Author: User
Tags foreach loop in php
I found a problem that is easy to make mistakes, but does not understand the principle, but does not understand the problem. if you encounter a similar problem, you can refer to it. The code is as follows:
Foreach ($ array as & $ row ){
$ Row = explode ('/', $ row );
}
Foreach ($ array as $ row ){
// Do something
}

In this case, a logic error occurs in the second loop. in the second loop, do something outputs $ row, and the output at the end of the loop is the second-to-last element, instead of the last

Write it like this
The code is as follows:
Foreach ($ array as & $ row ){
$ Row = explode ('/', $ row );
}
Unset ($ row );
Foreach ($ array as $ row ){
// Do something
}

Or write in the first loop.
The code is as follows:
Foreach ($ array as $ key => $ row ){
$ Array [$ key] = explode ('/', $ row );
}


Principles
Reference is used in the first loop. after the loop ends, $ row references the last element of the $ array. when the second loop starts, $ row variables are assigned a new value each cycle. in php, if a memory space is referenced, the value of this memory space is directly changed when it is changed, that is to say, when the first loop of the second foreach changes the value of the last element of $ array to the value of the first element of $ array, changed to the value of the second element. when the second-to-last loop is used, it is changed to the second-to-last element value. The value obtained in the last loop must be the second-to-last value.
Of course, this problem does not occur if php's for loop has a scope .....

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.