Note that there are some explanatory texts on larger screens.

plurals
  1. POCan you explain this odd behaviour with repeated values after looping with a reference?
    primarykey
    data
    text
    <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/8220399/strange-behaviour-after-loop-by-reference-is-this-a-php-bug">Strange behaviour after loop by reference - Is this a PHP bug?</a> </p> </blockquote> <h3><a href="http://ideone.com/zTv2i" rel="nofollow noreferrer">ideone</a></h3> <h3>code:</h3> <pre><code>&lt;?php $arr = array(array(1),array(2),array(3)); foreach($arr as &amp;$i) { print_r($i); } foreach($arr as $i) { print_r($i); } </code></pre> <h3>output</h3> <pre><code>Array ( [0] =&gt; 1 ) Array ( [0] =&gt; 2 ) Array ( [0] =&gt; 3 ) Array ( [0] =&gt; 1 ) Array ( [0] =&gt; 2 ) Array ( [0] =&gt; 2 ) </code></pre> <p>I know I just need to put an <code>unset($i)</code> after the first loop to fix it, but I can't really figure out what would cause the <code>2</code> to be repeated. It always seems to be the last value that is overwritten with the 2nd to last value. It doesn't seem to happen when the array items are primitives ('scalar' in PHP).</p> <p>I've ran into this problem a few times with reused variables when someone forgets to unset a reference. Really confused me the first time.</p> <h1>Duplicates</h1> <ul> <li><a href="https://stackoverflow.com/questions/4969243/strange-behavior-of-foreach">Strange behavior Of foreach</a></li> <li><a href="https://stackoverflow.com/questions/8901861/understanding-foreach-logic-with-references-why-is-the-1st-element-being-chang">Understanding foreach logic with references - Why is the 1st element being changed to &#39;two&#39;, the 2nd to &#39;three&#39;, and the third to &#39;three3&#39;?</a></li> <li><a href="https://stackoverflow.com/questions/8220399/strange-behaviour-after-loop-by-reference-is-this-a-php-bug">PHP Foreach Pass by Reference: Last Element Duplicating? (Bug?)</a></li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload