title: PHP array_merge is particularly slow and memory intensive when it is used in a loop
body: <p>I have a problem... I have done some research and I have been told that having an array_merge in a foreach can be particularly slow and memory intensive and i need an alternative for this block of code. But i'm not sure what is the best course to take</p>
  
  <p>Can anyone help?</p>
  
  <pre><code>/**
   * Parse long itrative tags
   *
   * Return array of matches for iterative tag pattern e.g. {%label%} to output the document label on this iteration of the loop
   *
   * @access  public
   * @return  array
   */
  
  function parse_long_iterative_tags($text)
  {
      $pattern = "/{%(?P&lt;type&gt;[A-Za-z0-9_?!]+):\((?P&lt;name&gt;.+)\)[\s]*(?P&lt;attributes&gt;[A-Za-z0-9\s_,:?.\/\-\|\(\)]*?){[\s]*(?P&lt;content&gt;(.*?[\s]*)*)[\s]*\}[\s]*end\\1\%}/";
      preg_match_all($pattern,$text,$matches);
      if(!empty($matches['content'])):
          $nested = implode("",$matches['content']);
          $sub_matches =  $this-&gt;parse_long_iterative_tags($nested);
          foreach($matches as $k=&gt;$v):
              $matches[$k] = array_merge($matches[$k],$sub_matches[$k]);
          endforeach;
          return $matches;
      else:
          return $matches;
      endif;
      return $matches;
  }
  </code></pre>