title: Alternative to foreach pass by reference
body: <p>I've come by a case where values in a foreach are passed by reference in order to modify the element, then at a later stage in the code, the same array is looped again to do some calculation but this time the elements are passed by value. The issue is that PHP retains the reference to the last element in the array in the first foreach, then <em>overwrites</em> that element when the next foreach starts if the local variable has the same name.</p>
  
  <p>Example code:</p>
  
  <pre><code>&lt;?php
  $a = array("a" =&gt; "foo");
  $b = array("b" =&gt; "bar");
  
  $x = array($a, $b);
  
  foreach ($x as &amp;$y) {}
  
  print_r($x);
  
  foreach ($x as $y) {}
  
  print_r($x);
  ?&gt;
  </code></pre>
  
  <p>This will yield</p>
  
  <pre>
  Array
  (
      [0] => Array
          (
              [a] => foo
          )
  
      [1] => Array
          (
              [b] => bar
          )
  
  )
  Array
  (
      [0] => Array
          (
              [a] => foo
          )
  
      [1] => Array
          (
              [a] => foo
          )
  
  )
  </pre>
  
  <p>This absurdity is stated in the PHP manual</p>
  
  <blockquote>
    <p><strong>Warning</strong> Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().</p>
  </blockquote>
  
  <p>And indeed, using <code>unset($y)</code> will resolve the issue. But this is very fragile and you cannot rely on the coder always remembering to unset a variable which scope isn't obvious. So my question is: Are there any good alternatives to foreach-pass-by-reference that eliminates the need to unset the variable afterwards?</p>