title: How to get X newest files from a directory in PHP?
body: <p>The code below is part of a function for grabbing 5 image files from a given directory.</p>
  
  <p>At the moment readdir returns the images 'in the order in which they are stored by the filesystem' as per the <a href="http://us3.php.net/manual/en/function.readdir.php" rel="noreferrer">spec</a>.</p>
  
  <p>My question is, how can I modify it to get the latest 5 images? Either based on the <code>last_modified</code> date or the filename (which look like 0000009-16-5-2009.png, 0000012-17-5-2009.png, etc.).</p>
  
  <pre><code>if ( $handle = opendir($absolute_dir) )
  {
      $i = 0;
      $image_array = array();
  
      while ( count($image_array) &lt; 5 &amp;&amp; ( ($file = readdir($handle)) !== false) )
      {
          if ( $file != "." &amp;&amp; $file != ".." &amp;&amp; $file != ".svn" &amp;&amp; $file != 'img' ) 
          {
              $image_array[$i]['url'] = $relative_dir . $file;
              $image_array[$i]['last_modified'] = date ("F d Y H:i:s", filemtime($absolute_dir . '/' . $file));
          }
  
          $i++;
      }
      closedir($handle);
  }
  </code></pre>