Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Some points to note when working with <code>foreach()</code>:</p> <p>a) <code>foreach</code> works on the <strong>prospected copy</strong> of the original array. It means foreach() will have SHARED data storage until or unless a <code>prospected copy</code> is not created <a href="http://php.net/manual/en/control-structures.foreach.php" rel="noreferrer">foreach Notes/User comments</a>.</p> <p>b) What triggers a <strong>prospected copy</strong>? Prospected copy is created based on the policy of <code>copy-on-write</code>, that is, whenever an array passed to foreach() is changed, a clone of original array is created.</p> <p>c) The original array and foreach() iterator will have <code>DISTINCT SENTINEL VARIABLES</code>, that is, one for the original array and other for foreach; see the test code below. <a href="http://php.net/manual/en/book.spl.php" rel="noreferrer">SPL</a> , <a href="http://www.php.net/manual/en/spl.iterators.php" rel="noreferrer">Iterators</a>, and <a href="http://www.php.net/manual/en/class.arrayiterator.php" rel="noreferrer">Array Iterator</a>.</p> <p>Stack&nbsp;Overflow question <em><a href="https://stackoverflow.com/questions/2728709">How to make sure the value is reset in a 'foreach' loop in PHP?</a></em> addresses the cases (3,4,5) of your question.</p> <p>The following example show that each() and reset() DOES NOT affect <code>SENTINEL</code> variables <code>(for example, the current index variable)</code> of the foreach() iterator.</p> <pre><code>$array = array(1, 2, 3, 4, 5); list($key2, $val2) = each($array); echo "each() Original (outside): $key2 =&gt; $val2&lt;br/&gt;"; foreach($array as $key =&gt; $val){ echo "foreach: $key =&gt; $val&lt;br/&gt;"; list($key2,$val2) = each($array); echo "each() Original(inside): $key2 =&gt; $val2&lt;br/&gt;"; echo "--------Iteration--------&lt;br/&gt;"; if ($key == 3){ echo "Resetting original array pointer&lt;br/&gt;"; reset($array); } } list($key2, $val2) = each($array); echo "each() Original (outside): $key2 =&gt; $val2&lt;br/&gt;"; </code></pre> <p><strong>Output:</strong></p> <pre><code>each() Original (outside): 0 =&gt; 1 foreach: 0 =&gt; 1 each() Original(inside): 1 =&gt; 2 --------Iteration-------- foreach: 1 =&gt; 2 each() Original(inside): 2 =&gt; 3 --------Iteration-------- foreach: 2 =&gt; 3 each() Original(inside): 3 =&gt; 4 --------Iteration-------- foreach: 3 =&gt; 4 each() Original(inside): 4 =&gt; 5 --------Iteration-------- Resetting original array pointer foreach: 4 =&gt; 5 each() Original(inside): 0=&gt;1 --------Iteration-------- each() Original (outside): 1 =&gt; 2 </code></pre>
 

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