5

We can get the files in a directory in PHP by

$files = new DirectoryIterator() 

after that is there an easy way to sort the items in a particular order for displaying them? thanks.

hakre
  • 193,403
  • 52
  • 435
  • 836
nonopolarity
  • 146,324
  • 131
  • 460
  • 740

2 Answers2

10

It doesn't look like there is a way to sort the data within the iterator.

You could place the display data into an intermediary array, with a key of the value you wish to sort by, and call ksort() on the array. This will take two passes over the data however.

$path = ".";
$files = new DirectoryIterator($path);
$files_array = array();

while($files->valid()) {
        // sort key, ie. modified timestamp
        $key = $files->getMTime();
        $data = $files->getFilename();
        $files_array[$key] = $data;
        $files->next();
}
ksort($files_array);
foreach($files_array as $key => $file){
    print $key . " => " . $file . "\n";
}

edit:

if you place all of the information that you want to output for the files in the array values, you can simply implode() the array afterwards, instead of looping through the data once again.

pce
  • 5,571
  • 2
  • 20
  • 25
gapple
  • 3,463
  • 22
  • 27
  • In this example files will get "lost" if they happen to have the same modification time. You can avoid this by appending the filename to the key. – wedi Jul 11 '20 at 23:25
-4
$files = new DirectoryIterator($path);
$i = 0;
$paths = array();
while($files->valid()) {
    $paths[$i++] = $files->getFileName();
    $files->next();
}
sort($paths)

May be what you are looking for, you can always of course apply the sort function to sort the paths depending on your preference after that.

user127706
  • 50
  • 4
  • This "sorts" the files into the same order returned by DirectoryIterator, i.e. not sorted. The accepted answer specifies a relevant key for sorting. – Thunder Rabbit Jan 18 '21 at 01:17