Introduction to _php tips for using foreach and references in PHP to cause bug problems in your program

Source: Internet
Author: User
Copy Code code as follows:

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

The two cycle is meant to be: the first loop needs to modify the contents of the element in the loop, so use the reference; But the second loop just treats $r as a temporary variable. But why has the value of the $a [1] changed?

When the $a iteration is complete, the $r is a reference to the $a [1], changing the value of the $r to change the $a [1]. At this point, you can be surprised that the code did not modify the $r, and did not modify the $a [1] ah?

In fact, foreach is manipulating the copy of an array, so the latter iteration is equivalent to:
Copy Code code as follows:

for ($i =0; $i <count ($b); $i + +) {
$r = $b [$i]; Modified the $r! equivalent to $a [1] = $b [$i];
}

To avoid this, after the first iteration, you should execute the
Copy Code code as follows:

Unset ($R);

Deletes $r this variable (reference variable) from the current environment.

Even if it is not the previous example, after the first iteration, it is still quite possible to execute a similar statement:
Copy Code code as follows:

$r = 123;

A loop variable is generally a temporary variable, and the same variable name represents something different in the code, but the scope of the variable is outside the loop. This is the disadvantage of this scoping rule, plus the bad of "variable is not declared to be used", plus the variable has no type of disadvantage.

Therefore, the use of reference variables in PHP, should be used after the reference should be unset (). All variables should be unset () before they are used.

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.