Search code examples
phpsortingscandir

PHP scandir results: sort by folder-file, then alphabetically


PHP manual for scandir: By default, the sorted order is alphabetical in ascending order.

I'm building a file browser (in Windows), so I want the addresses to be returned sorted by folder/file, then alphabetically in those subsets.

Example: Right now, I scan and output

Aardvark.txt
BarDir
BazDir
Dante.pdf
FooDir

and I want

BarDir
BazDir
FooDir
Aardvark.txt
Dante.pdf

Other than a usort and is_dir() solution (which I can figure out myself), is there a quick and efficient way to do this?

The ninja who wrote this comment is on the right track - is that the best way?


Solution

  • Does this give you what you want?

    function readDir($path) {
    
        // Make sure we have a trailing slash and asterix
        $path = rtrim($path, '/') . '/*';
    
        $dirs = glob($path, GLOB_ONLYDIR);
    
        $files = glob($path);
    
        return array_unique(array_merge($dirs, $files));
    
    }
    
    $path = '/path/to/dir/';
    
    readDir($path);
    

    Note that you can't glob('*.*') for files because it picks up folders named like.this.