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...