Home >Backend Development >PHP Tutorial >A pitfall of PHP cycles and references, PHP circular references_PHP tutorial
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>
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"
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