Precautions for using references in the foreach loop in PHP _ PHP Tutorial

Source: Internet
Author: User
Note when using references in the foreach loop in PHP. The code for copying the code is as follows: foreach ($ arrayas} foreach ($ arrayas $ row) {dosomething} writes the code in the second loop with a logical error. 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 .....

The http://www.bkjia.com/PHPjc/322706.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/322706.htmlTechArticle code is as follows: foreach ($ array as} foreach ($ array as $ row) {// do something} writes so that a logical error occurs in the second loop, add do something in the second loop...

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.