title: foreach doesn't print altered array properly
body: <p>I am trying to print an array using <strong>foreach</strong> and while printing, if a certain $key comes up, I want to make changes to the array. Problem is, even though the array gets changed, the changes do not get printed. </p>
  
  <p>In the example below, you will find: </p>
  
  <ul>
  <li>function I use to change the array;</li>
  <li>an array first printed with no changed;</li>
  <li>then echo print-out in with changes during the process - all using foreach;</li>
  <li><p>another print-out of the same table, but this time with changes.</p>
  
  <pre><code>&lt;?php
  
  function insert_before_key($array, $key, $data = NULL){
      if (($offset = array_search($key, array_keys($array))) === false){
          $offset = count($array); 
      }
      return array_merge(array_slice($array, 0, $offset), (array) $data, array_slice($array, $offset));
  }
  
  $array = array(
      "no_color"  =&gt;  "blank",
      "color1"    =&gt;  "red",
      "color2"    =&gt;  "green",
      "color3"    =&gt;  "blue",
      );
  
  echo "&lt;pre&gt;";
  print_r($array);
  echo "&lt;/pre&gt;";
  
  foreach ($array as $key =&gt; $value) {
      echo $key . ": " . $value . "&lt;br /&gt;";
      if ($key === "color1"){
          $array = insert_before_key($array, "color2", array("color1.5" =&gt; "yellow"));
      }
  }
  
  echo "&lt;pre&gt;";
  print_r($array);
  echo "&lt;/pre&gt;";
  
  echo "&lt;br /&gt;";
  
  ?&gt;
  </code></pre></li>
  </ul>
  
  <p>Note that the new $key is to jump in <strong>AFTER</strong> current $key, so I would expect it to come up.
  Any idea why this happens ? </p>
  
  <p><strong>EDIT:</strong> </p>
  
  <p>Played a bit more with foreach and I think it must be caching the keys or something...</p>
  
  <pre><code>    &lt;?php
      $test_array = array(0,1,2,3,4,5,6,7,8,9);
  
      foreach ($test_array as $key =&gt; $value) {
          if ($key === 5){$test_array[7] = $test_array[7]+1;}
          echo $key . ": " . $value . "&lt;br /&gt;";
      }
  
      print_r($test_array);
      ?&gt;
  </code></pre>
  
  <p>The above will display UNCHANGED echo, but CHANGED print_r.</p>