Php loops and references

Source: Internet
Author: User
Php loop and reference code

$ Arr = array ('a' => 'a11', 'B' => 'b22', 'C' => 'c33 ',); foreach ($ arr as $ k =>&$ v) {// Do somethind} foreach ($ arr as $ k =>$ v) {var_dump ($ v );}

What will var_dump output with such code? You can try it.

String (3) "a11" string (3) "b22" string (3) "b22"

In the result, the third row is the value of key = 'B'. the problem lies in the reference of the first loop.

Today, I stepped on such a pitfall and it took a long time to check the problem. In short, the reference used by the foreach loop is retained after the loop ends. php.net is rewritten:

Warning

Reference of a $ valueand the last array element remain even after the foreachloop. It is recommended to destroy it by unset ().

For the above example, after the first loop ends, the $ v reference still exists. because the variables in the two loops are named the same, $ v is assigned each time starting from the second loop. until the end, $ v is set

The value of the previous element.

The principle is very simple, and the document is clearly written. However, if you encounter bugs in your work, it will take a long time to locate the issue. you should pay attention to the following when you need to write code:

1. reduce the use of references

2. if you need to use a reference in foreah, use the function to encapsulate it.

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.