how to sort directories above files in php

124 Views Asked by At

For a filemanagement, I used to render the folders and files with scandir and a foreach and sort them: Directories first, then Files

$files = array_diff( scandir($dir), array(".", "..", "tmp") );
usort ($files, create_function ('$a,$b', '
                        return  is_dir ($a)
                            ? (is_dir ($b) ? strnatcasecmp ($a, $b) : -1)
                            : (is_dir ($b) ? 1 : (
                                strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION)) == 0
                                ? strnatcasecmp ($a, $b)
                                : strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION))
                            ))
                        ;
                    '));

foreach($files as $file){

  if(is_dir($dir.'/'.$file)) {
         echo $file; // $dir is directory(folder)
  } else {
         echo $file;
  }

Because scandir is getting slower when rendering a lot of files, I now use the opendir and readdir like below:

if ($handle = opendir($dir)) {
                while (false !== ($file = readdir($handle))) {
                    if ($file != "." && $file != ".." && $file != "tmp") {  //ignoring dot paths under linux and tmp folder

if(is_dir($dir.'/'.$file)) {
       echo $file; // $dir is directory(folder)
} else {
       echo $file;
}

But now the sorting does not work anymore. How can I sort the Directories first and then the files now?

0

There are 0 best solutions below