title: PHP Sort Files In Directory by Type
body: <p>I wrote the following PHP code to display files in a directory. It uses JQuery to expand folders. Everything works fine but right now it displays all files in alphabetical order mixing file types.</p>
  
  <p>I'd like to keep the alphabetical order but display folders and files separately. How can I sort the displayed files so Folders are displayed on top and other files are displayed bellow.</p>
  
  <p>In other words, how do I sort the files by file type?</p>
  
  <p>Thank you very much!</p>
  
  <pre><code>&lt;?php
  $path = ROOT_PATH;
  $dir_handle = @opendir($path) or die("Unable to open $path");
  list_dir($dir_handle,$path);
  
  function list_dir($dir_handle,$path)
  {
      echo "&lt;ul class='treeview'&gt;";
  
      while (false !== ($file = readdir($dir_handle))) 
      {
          $dir =$path.'/'.$file;
          if(is_dir($dir) &amp;&amp; $file != '.' &amp;&amp; $file !='..' )
          {
              $handle = @opendir($dir) or die("undable to open file $file");
              echo '&lt;li class="folder"&gt;&lt;a href="#" class="toggle"&gt;'.$file.'&lt;/a&gt;&lt;/li&gt;';
              list_dir($handle, $dir);
          }
          elseif($file != '.' &amp;&amp; $file !='..')
          {
              echo '&lt;li class="file"&gt;&lt;a href="file-details.php?file='.$dir.'" class="arrow_icon modal"&gt;'.$file.'&lt;/a&gt;&lt;/li&gt;';
          }
      }
  
      echo "&lt;/ul&gt;";
  
      closedir($dir_handle);
  }
  ?&gt;
  </code></pre>