title: How to sort by date using PHP opendir()
body: <p>I have  a directory full of files that I am trying to echo out. If  the file is an image, the image itself is echoed out. If the file is not an image, the name of the file is echoed out.</p>
  
  <p>This code below works perfectly however I can't seem to get the order sorted by date. The files are randomly echoed out. </p>
  
  <p>How would I make it so that the files are sorted by last modified (latest first).</p>
  
  <pre><code>&lt;?php
  
  
  $blacklist = array("index.php");
  $ext = pathinfo($files, PATHINFO_EXTENSION);
  
  if ($handle = opendir('.')) {
  
      $valid_image = array("jpg", "jpeg", "png", "gif");
  
      while (false !== ($entry = readdir($handle))) { 
         krsort($entry);
  
          if ($entry != "." &amp;&amp; $entry != ".." &amp;&amp; !in_array($entry, $blacklist)) {
  
              $exploded = explode('.', $entry);
  
              if(in_array(end($exploded), $valid_image))
              {
                echo "&lt;div&gt;&lt;h4&gt;"; echo date('d F Y', filemtime($file)) . "&lt;/h4&gt;&lt;a href='" . $entry . "'&gt;&lt;img src='".$entry."'&gt;&lt;/a&gt;&lt;/div&gt;&lt;hr&gt;";
              }
              else
              {
                echo "&lt;div&gt;&lt;h4&gt;"; echo date('d F Y', filemtime($file)) . "&lt;/h4&gt;&lt;a href='" . $entry . "'&gt;" . $entry . "&lt;/a&gt;&lt;/div&gt;";
              }
          } 
      }
      closedir($handle);
  }
  ?&gt;
  </code></pre>