title: How to properly paginate a foreach loop
body: <p>I have a project I am working on, where I scan a directory and pull all of the images from the directory that will display the gallery images. Problem is, some galleries have 300+ images and this is causing a lag. I have looked around, but have not found a proper way of getting my code to paginate. Here is my code snippet of where I am running the foreach loop and getting each image source from the directory:</p>
  
  <pre><code>/** get the model's gallery
  ===================================================== **/
  if(isset($_GET['count'])){
      $photo_count =  $_GET['count'];    
  }
  if(isset($_GET['model_dir'])){
      $model_dir = $_GET['model_dir'];
  
      /** get the higres gallery images
      ===================================================== **/
      $root_directory     = $_SERVER['DOCUMENT_ROOT'];
      $photo_directory    = "{$root_directory}/members/content/model_gallery/{$model_dir}";
      $gallery_list       = scandir($photo_directory);
      $gallery_list       = array_diff($gallery_list, array('.', '..'));
      foreach($gallery_list as $gallery){
          echo "
          &lt;a href='{$index_url}join.php'&gt;
          &lt;img alt='' src='{$site_url}members/content/model_gallery/{$model_dir}/{$gallery}'
          data-image='{$site_url}members/content/model_gallery/{$model_dir}/{$gallery}'
          data-description=''&gt;
          &lt;/a&gt;
          "; 
      }  
  }
  </code></pre>
  
  <p>Any ideas on how I could go about paginating this code would be greatly appreciated.</p>