Pinkie Pinkie - 1 year ago 201
PHP Question

php DirectoryIterator sort files by date

I'm using php's

class to list files in a directory. I can't however figure out an easy way to sort files by date. How is this done with DirectoryIterator

$dir = new DirectoryIterator('.');
foreach ($dir as $fileinfo) {
echo $fileinfo->getFilename() . '<br>';

What if i name my files like whatever_2342345345.ext where the numbers represents time in milliseconds so each file has a unique number. How can we sort by looking at the numbers after underscore

Answer Source

If you need to sort, build an array and sort that.

$files = array();
$dir = new DirectoryIterator('.');
foreach ($dir as $fileinfo) {     
   $files[$fileinfo->getMTime()][] = $fileinfo->getFilename();


This will build an array with the modified time as the key and an array of filenames as the value. It then sorts via ksort(), which will give you the filenames in order of time modified.

If you then want to re-flatten the structure to a standard array, you can use...

$files = call_user_func_array('array_merge', $files);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download