Skip to content

Instantly share code, notes, and snippets.

@gourneau
Created December 1, 2011 10:37
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gourneau/1415698 to your computer and use it in GitHub Desktop.
Save gourneau/1415698 to your computer and use it in GitHub Desktop.
PHP List Directories by Date
<?php
//This little PHP script is the most elegant way
//I could find the list directories and
//files with PHP and sort by date
//thanks to StackOverflow
$files = array();
$dir = new DirectoryIterator('.');
foreach ($dir as $fileinfo) {
$files[$fileinfo->getMTime()] = $fileinfo->getFilename();
}
//krsort will sort in reverse order
krsort($files);
//just print out the file names
//excluding this file (named index.php and the dir "." )
foreach($files as $file){
if ($file == "index.php" or $file == "." ){
}else{
print $file;
print "</br>";
}
}
?>
@Pretzel911
Copy link

Testing out how to do this, and noticed a bug. Simply if multiple files have the same modified date, only one get's listed.
ex:
https://imgur.com/a/XKVXlwe

I might be late to the party, it's a good starting point for me either way.

@chojnicki
Copy link

@Pretzel911 You are right.
For anyone else with this problem - simple fix for this is using multidimensional array.

Replace
$files[$fileinfo->getMTime()] = $fileinfo->getFilename();
with
$files[$fileinfo->getMTime()][] = $fileinfo->getFilename();

then we need to somehow flatten this array. I'm using Laravel with this so I have array_flatten helper function available, but with plain PHP it could be done by simple nested foreach like this

$array = []; foreach ($files as $group) { foreach ($group as $item) { $array[] = $item; } }

Not that short and elegant as original gist, but it works...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment