Home >Backend Development >PHP Tutorial >Things to pay attention to when using references in foreach loop in PHP_PHP Tutorial

Things to pay attention to when using references in foreach loop in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:32:58957browse

Copy code The code is as follows:

foreach ($array as &$row) {
$row = explode('/' , $row);
}
foreach ($array as $row) {
//do something
}

Written like this, in the second loop it will There is a logic error. The place to do something in the second loop is to output $row. When the loop reaches the last one, the output is the penultimate element, not the last

. It should be written like this
Copy code The code is as follows:

foreach ($array as &$row) {
$row = explode('/' , $row);
}
unset($row);
foreach ($array as $row) {
//do something
}

Or write the first loop like this
Copy the code The code is as follows:

foreach ($array as $key => $ row) {
$array[$key] = explode('/', $row);
}


Tell me the principle
The first loop uses a reference. After the loop ends, $row refers to the last element of the $array array. When the second loop starts, the $row variable will be assigned a new value each time it loops. In PHP , if a memory space is referenced, then when it is changed, the value of this memory space is directly changed. That is to say, when the second foreach loops for the first time, the value of the last element of $array It is changed to the value of the first element of $array. During the second loop, it is changed to the value of the second element. During the penultimate loop, it is changed to the value of the second to last element. And finally The value obtained during a loop must be the penultimate value
Of course, if the for loop of PHP has a scope, this problem will not occur...

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322706.htmlTechArticleCopy the code as follows: foreach ($array as } foreach ($array as $row) { //do something } Written like this, there will be a logic error in the second loop. Add the do something in the second loop...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn