1
PHP Date Sort using scandir()
New Here
,
/t5/dreamweaver-discussions/php-date-sort-using-scandir/td-p/14422597
Feb 14, 2024
Feb 14, 2024
Copy link to clipboard
Copied
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
TOPICS
Code
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting.
Learn more
LEGEND
,
LATEST
/t5/dreamweaver-discussions/php-date-sort-using-scandir/m-p/14423177#M227481
Feb 14, 2024
Feb 14, 2024
Copy link to clipboard
Copied
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>";
}
}
?>
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting.
Learn more

