0

I have the below code that I run to list files within a directory. I would like to sort the output by some way. Preferably filename or by date of upload. Is this even possible?

<?php
  if ($handle = opendir('./xyz')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
          $thelist .= '<a href="./abc/xyz/'.$file.'">'.$file.'</a><br>';
        }
    }
  closedir($handle);
  }
?>
<h1>List of files:</h1>
<ul><?php echo $thelist; ?></ul>

EDIT: New code with update.

<?php
array_multisort(array_map('filectime', $files = glob('./xyz/*.*')), SORT_DEC, $files);
?>

<h1>List of files:</h1>
<ul><?php foreach($files as $file) {
    echo '<a href="./abc/'.$file.'">'.$file.'</a><br>';
}
?></ul>
  • 2
    Possible duplicate of [PHP readdir() not returning files in alphabetical order](https://stackoverflow.com/questions/541510/php-readdir-not-returning-files-in-alphabetical-order) – CBroe Apr 04 '18 at 17:38

2 Answers2

0

You can't sort with readdir which reads them in the order that they are stored in the file system. You can read them into an array and sort that. array_multisort works well and you can replace filectime with other functions:

array_multisort(array_map('filectime', $files = glob('./xyz/*.*')),
                SORT_ASC, $files);
  • This gets all files into an array $files, maps to filectime to get the time, sorts on that and then sorts the $files array on that.

  • For alphabetical just use sort or rsort after glob.

Once you have the sorted array just loop it and display or build your string as you were:

foreach($files as $file) {
    echo '<a href="./abc/xyz/'.$file.'">'.basename($file).'</a><br>';
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
-1

have you tried use a kind of tranformation of the names in a Array, and after this tried to sorting ?...See this : is a basic sorting function

<?php $cars = array("Volvo", "BMW", "Toyota"); sort($cars); ?>