Introduction to the problem of program BUG caused by using foreach and references in PHP_PHP Tutorial

WBOY
Release: 2016-07-21 15:16:40
Original
726 people have browsed it

Copy code The code is as follows:

$a = array(1, 2);
$b = array(11, 12 );
foreach($a as &$r){
}
foreach($b as $r){
}
echo $a[1]; // Output 12

The original intention of the two loops may be: the first loop needs to modify the content of the element in the loop, so it uses a reference; but the second loop just uses $r as a temporary variable. But , why did the value of $a[1] change?

When the iteration of $a is completed, $r is a reference to $a[1]. Changing the value of $r means changing $a [1]. At this time, you may be surprised that $r has not been modified in the code, nor has $a[1] been modified?

In fact, foreach operates on a copy of the array, so, after One iteration is equivalent to:
Copy code The code is as follows:

for($i=0; $i$r = $b[$i]; // Modified $r! Equivalent to $a[1] = $b[$i];
}

In order to avoid this situation, you should execute
Copy code after the first iteration. The code is as follows:

unset($r);

Delete the $r variable (reference variable) from the current environment.

Even if it is not the previous example, after the first iteration, It is still very possible to execute similar statements again:
Copy code The code is as follows:

$r = 123;

Loop variables are generally temporary variables. The same variable name represents different things in different places in the code, but the scope of the variable exists outside the loop. This is the disadvantage of this scope rule, plus In addition to the disadvantages of "variables can be used without declaring them", there is also the disadvantage of variables having no type.

So, when using reference variables in PHP, you should unset() them after the reference is used. All variables are in You should unset() before using it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325872.htmlTechArticleCopy the code as follows: $a = array(1, 2); $b = array(11, 12) ; foreach($a as // Output 12 The original intention of the two loops may be: the first loop needs to modify the content of the element in the loop...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!