Home > Backend Development > PHP Tutorial > A pitfall of PHP cycles and references, PHP circular references_PHP tutorial

A pitfall of PHP cycles and references, PHP circular references_PHP tutorial

WBOY
Release: 2016-07-12 08:59:37
Original
1684 people have browsed it

A pitfall of PHP loops and references, PHP loop references

on the code

<span>$arr</span> = <span>array</span><span>(
    </span>'a'=> 'a11',
    'b'=> 'b22',
    'c'=> 'c33',<span>
);  
</span><span>foreach</span> (<span>$arr</span> <span>as</span> <span>$k</span>=>&<span>$v</span><span>){
    </span><span>//</span><span> Do somethind</span>
<span>}
</span><span>foreach</span> (<span>$arr</span> <span>as</span> <span>$k</span>=><span>$v</span><span>){
    </span><span>var_dump</span>(<span>$v</span><span>);
}</span>
Copy after login

With such code, what will var_dump output? You can try it, the answer is

<span>string</span>(3) "a11"
<span>string</span>(3) "b22"
<span>string</span>(3) "b22"
Copy after login

In the result, the third line becomes the value of key='b'. The problem lies in the first circular reference.

I stepped into such a pit today, and it took me a long time to check the problem. Simply put, the references used in the foreach loop are retained after the loop ends. php.net rewrote:

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 the above example, after the first loop ends, the $v reference still exists. Since the variables of the two loops are named the same, $v will be assigned a value every time when the second loop starts. Until the end, $v is Set to

The value of the previous element.

The principle is very simple, and the documentation is clearly written. But if you encounter related bugs at work, it will be very difficult, and it will take a long time to locate. When you still need to write code, pay attention to:

1. Reduce the use of references

2. If you need to use a reference in foreah, you should encapsulate it with a function

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1098446.htmlTechArticleA pitfall in PHP loops and references. PHP loops reference the code $arr = array ( 'a'= ' a11', 'b'= 'b22', 'c'= 'c33', ); foreach ( $arr as $k = $v ){ // Do somethind } foreach ( $arr as...
Related labels:
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