PHP loops with reference to a pit, PHP loop reference _php Tutorial

Source: Internet
Author: User

PHP loops with reference to a pit, PHP loop reference


On the Code

$arr Array (    ' a ' = ' A11 ',    ' b ' = ' B22 ',    ' c ' = ' C33 ',);   foreach ($arras$k=>&$v) {    // do Somethind}foreach ($arras$k= =$v  ) {    var_dump($v);}

What will the var_dump output like in this code? You can try, the answer.

string (3) "A11"string(3) "B22"string(3) "B22"

In the result, the third line becomes the value of key= ' B '. The problem is the reference to the first loop.

Today, stepping on a hole like this, it took a long time to check the problem. In short, the Foreach Loop uses a reference that is retained after the loop has ended. Php.net emphatically wrote:

Warning

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset ().

For this example, the $v reference still exists after the first loop has ended. Since the variables of the two loops are named consistent, the second loop starts, and $v are assigned each time. Until the end, $v was set to

The value of the previous element.

The principle is simple, the document is written plainly. But if the work encountered the relevant bug is very pit, positioning takes a long time. You have to pay attention when you need to write the code:

1. Reduce the use of references

2. If you need to use references in Foreah, you should use functions to encapsulate them

http://www.bkjia.com/PHPjc/1098446.html www.bkjia.com true http://www.bkjia.com/PHPjc/1098446.html techarticle PHP loops with reference to a pit, PHP loop reference on Code $arr = Array (' A ' = ' A11 ', ' b ' = ' b22 ', ' c ' = ' c33 ',); foreach ($arr as $k = $v) {//Do som Ethind} foreach ($arr as ...

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