Skip to main content
Participant
February 14, 2024
Question

PHP Date Sort using scandir()

  • February 14, 2024
  • 1 reply
  • 459 views

I have been racking my brain with this with no obvious solution. For the life of me I cannot sort the following by date. When I run it I get the following output where 2024-02-01 should be before 2024-02-13:

  • 2024-01-30
  • 2024-02-13
  • 2024-02-14
  • 2024-02-01

//PATH

$dirPath    = 'INuploads';
// $dirPath contain path to directory whose files are to be listed 
$files = scandir($dirPath); 
//SORT
usort($files);
//PRINT OUT RESULTS
foreach ($files as $file) {
    $filePath = $dirPath . '/' . $file;
    if (is_file($filePath)) {
        echo "<a href='INuploads/$file' target=new>" . $file . "</a>". date ("Y-m-d", filemtime("$dirPath/$file"));
     }
 
Any suggestions would be greatly appriciated. I have tried many different variotions of this, arsort, sort, ksort
This topic has been closed for replies.

1 reply

Legend
February 14, 2024

Does this improve anything:

 

<?php
$dirPath = 'INuploads';
$files = scandir($dirPath);

function sortFilesFunction($a, $b) {
return strtotime($b) - strtotime($a);
}

sort($files, "sortFilesFunction");

foreach($files as $file) {
if (!in_array($file, array(".", ".."))) {
echo "<p><a href='INuploads/$file' target='new'>$file</a></p>";
}
}

?>