Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>After the first foreach loop, <code>$item</code> is still a reference to some value which is also being used by <code>$arr[2]</code>. So each foreach call in the second loop, which does not call by reference, replaces that value, and thus <code>$arr[2]</code>, with the new value.</p> <p>So loop 1, the value and <code>$arr[2]</code> become <code>$arr[0]</code>, which is 'foo'.<br> Loop 2, the value and <code>$arr[2]</code> become <code>$arr[1]</code>, which is 'bar'.<br> Loop 3, the value and <code>$arr[2]</code> become <code>$arr[2]</code>, which is 'bar' (because of loop 2).</p> <p>The value 'baz' is actually lost at the first call of the second foreach loop.</p> <h2>Debugging the Output</h2> <p>For each iteration of the loop, we'll echo the value of <code>$item</code> as well as recursively print the array <code>$arr</code>.</p> <p>When the first loop is run through, we see this output:</p> <pre><code>foo Array ( [0] =&gt; foo [1] =&gt; bar [2] =&gt; baz ) bar Array ( [0] =&gt; foo [1] =&gt; bar [2] =&gt; baz ) baz Array ( [0] =&gt; foo [1] =&gt; bar [2] =&gt; baz ) </code></pre> <p>At the end of the loop, <code>$item</code> is still pointing to the same place as <code>$arr[2]</code>.</p> <p>When the second loop is run through, we see this output:</p> <pre><code>foo Array ( [0] =&gt; foo [1] =&gt; bar [2] =&gt; foo ) bar Array ( [0] =&gt; foo [1] =&gt; bar [2] =&gt; bar ) bar Array ( [0] =&gt; foo [1] =&gt; bar [2] =&gt; bar ) </code></pre> <p>You'll notice how each time array put a new value into <code>$item</code>, it also updated <code>$arr[3]</code> with that same value, since they are both still pointing to the same location. When the loop gets to the third value of the array, it will contain the value <code>bar</code> because it was just set by the previous iteration of that loop.</p> <h2>Is it a bug?</h2> <p>No. This is the behavior of a referenced item, and not a bug. It would be similar to running something like:</p> <pre><code>for ($i = 0; $i &lt; count($arr); $i++) { $item = $arr[$i]; } </code></pre> <p>A foreach loop isn't special in nature in which it can ignore referenced items. It's simply setting that variable to the new value each time like you would outside of a loop.</p>
 

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