Search code examples
phparrayssortingalphabetical

Order an array containing file paths by alphabetical order in PHP


I have an array that contains the full path to many files. I need the array ordered alphabetically, but only by the basename of the file (file1.exe)

For example:

/path/2/file3.exe

/path/2/file4.exe

/path/to/file2.exe

/path/to/file1.exe

I expect the output to look like this:

/path/to/file1.exe

/path/to/file2.exe

/path/2/file3.exe

/path/2/file4.exe

The hard part I'm having is finding a way to make it ignore the directory when ordering. I will still need the file paths, but I just want it to reorder only factoring the basename, not the whole string.

Any ideas? Thanks


Solution

  • You can use usort, with a callback that compares the basename of each file name. For example:

    $files = array('/path/to/file3.exe',
                   '/path/to/file4.exe',
                   '/path/2/file2.exe',
                   '/path/2/file1.exe'
                  );
    
    usort($files, function ($a, $b) {
        return strcmp(basename($a), basename($b));
    });
    
    print_r($files);
    

    Output:

    Array
    (
        [0] => /path/2/file1.exe
        [1] => /path/2/file2.exe
        [2] => /path/to/file3.exe
        [3] => /path/to/file4.exe
    )
    

    Demo on 3v4l.org