title: How to reduce loops in array traversal in php
body: <p>How could I reduce the number of loops in my code. Current code is a dummy example but as I am scraping content from a URL and it contains around 6K-7K li traversal to scrap data so speed is a concern in my app.</p>
  
  <p>1) I am scraping data from a URL using Simple PHP DOM parser, so my first concern is whether it is a relevant way to traverse DOM for scraping data(around 6K-7K li elements) or <code>file_get_contents()</code> will be an appropriate.</p>
  
  <p>2) How do i reduce the number of loops in the below mentioned code, I tried but fails-</p>
  
  <p>My whole code</p>
  
  <pre><code>&lt;?php
  $arrunsort     = array('ab','ad','ar','cd','cb','sc','si','wa','za');
  $prevLabel     = array();
  $currLabelarr  = array();
  $newarr        = array();
  foreach( $arrunsort as $sortelem )
  {
      $currLabel = substr($sortelem, 0, 1);
      if( $currLabel !== $prevLabel )
      {
          //echo '&lt;h2&gt;',strtoupper($currLabel),'&lt;/h2&gt;','&lt;br&gt;';
          $currLabelarr[] = $currLabel;
          $prevLabel = $currLabel;
      }
  }
  
  foreach($currLabelarr as $arrkeymatch) 
  {
      $newarr[$arrkeymatch] = array();
      $i = 0;
      foreach($arrunsort as $value) 
      {
          if( $arrkeymatch == (substr($value, 0, 1)) )
          {
              //echo '&lt;li&gt;',$value,'&lt;/li&gt;';
              $newarr[$arrkeymatch][$i] = $value;
              $i++; 
          }   
      }
  }
  
  
  foreach($newarr as $key=&gt; $val)
  {
      echo "&lt;h3&gt;",$key,'&lt;/h3&gt;';
      echo '&lt;ul&gt;';
      foreach($val as $myval)
      {
          echo '&lt;li&gt;',$myval, '&lt;/li&gt;';
      }
      echo '&lt;/ul&gt;';
  }
  </code></pre>
  
  <p>Now my tries to reduce the number of loops-</p>
  
  <ul>
  <li>Comment the last <code>foreach</code> loop</li>
  <li>Uncomment <code>echo '&lt;h2&gt;',strtoupper($currLabel),'&lt;/h2&gt;','&lt;br&gt;';</code> &amp;
  <code>echo '&lt;li&gt;',$value,'&lt;/li&gt;';</code></li>
  </ul>
  
  <p>But the li items are coming below, let me know how could I solve this to minimize loops.</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>In the meantime I checked <a href="https://stackoverflow.com/questions/4218623/caching-a-php-array">Caching</a> but as a noob I am not very sure if it a genuine method of caching in my case.</p>