Variables in the PHP foreach Loop

Source: Internet
Author: User

A strange phenomenon occurred when using foreach, where the last value of an array variable was somehow modified, and the PHP manual foreach description found

Warning

The $value reference of the last element of the array remains after the Foreach loop. It is recommended to use unset () to destroy it.

There is such a warning. Use the Unset method or use a different variable name.

For example

$a =[1,2];foreach ($a as $key = = $value) {    $a [$key]= $value +1;} echo $value;//Output 2

If a pointer is used in $ A, the value of the variable with the same name will be affected, with the following result:

$a =[1,2]; $b =[3,4];foreach ($a as $key =>& $value) {    $a [$key]= $value +1;} Print_r ($a); foreach ($b as $value) {    $value + +;} Print_r ($a);p rint_r ($b); the output is as follows array (    [0] = 2    [1] = 3) array (    [0] = 2    [1] + 5) Array (    [ 0] = 3    [1] = 4)

If you use pointers or use unset, they are unaffected

$a =[1,2]; $b =[3,4];foreach ($a as $key =>& $value) {    $a [$key]= $value +1;} Print_r ($a); foreach ($b as & $value) {    $value + +;} Print_r ($a);p rint_r ($b); Enter the following array (    [0] = 2    [1] = 3) 3Array (    [0] = 2    [1] = 3) Array ( C14/>[0] + 4    [1] = 5)

Using unset

$a =[1,2]; $b =[3,4];foreach ($a as $key =>& $value) {    $a [$key]= $value +1;} Print_r ($a), unset ($key, $value), foreach ($b as $key = $value) {    $b [$key]= $value +1;} Print_r ($a);p rint_r ($b); the output is as follows array (    [0] = 2    [1] = 3) array (    [0] = 2    [1] + 3) array (    [ 0] = 4    [1] = 5)

Variables in the PHP foreach 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.