Search code examples
phpsortingreaddir

How to sort the contents of a directory alphabetically with sub directorys appearing before normal files?


I need to sort the contents of a directory in ascending order (alphabetically). The directories must appear before files even if the directory's name would appear after a files name (alphabetically). The same way file explorers do, they list directories sorted then they list the files sorted.

I am using the following code which gives me a sorted list alphabetically but it does not advances the directories first:

if($handler = opendir($dir))
{
    while (($sub = readdir($handler)) !== FALSE)
    {
        // ...
    }    
    closedir($handler); 
}

Solution

  • A straightforward way to achieve that would be to populate an array with pairs like [is_file(path), path], sort this array (php will automatically sort by the first and then by the second element) and finally remove the is_file bit:

    $path = 'somedir';
    $dir = [];
    
    // populate
    foreach(glob("$path/*") as $f)
        $dir []= [is_file($f), $f];
    
    // sort
    sort($dir);
    
    // remove
    $dir = array_map('end', $dir);
    
    // PROFIT
    print_r($dir);