php DirectoryIterator sort files by date

I’m using php’s DirectoryIterator 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

<?php
 $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

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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();
}

ksort($files);

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);

Solution 2

If you still want to access all the data available at DirectoryIterator (e.g. isDot() getSize() etc) a possible way is to store the Iterator key on the array you are going to sort, and seek the DirectoryIterator later.

$sorted_keys = array();
$dir_iterator = new DirectoryIterator('.');

foreach ( $dir_iterator as $fileinfo )
{
    $sorted_keys[$fileinfo->getMTime()] = $fileinfo->key();
}

ksort($sorted_keys);

/* Iterate `DirectoryIterator` as a sorted array */
foreach ( $sorted_keys as $key ) 
{
    $dir_iterator->seek($key);
    $fileinfo = $dir_iterator->current();

    /* Use $fileinfo here as a normal DirectoryIterator */
    echo $fileinfo->getFilename() . '  ' . $fileinfo->getSize() . '<br>';
}

Solution 3

In case multiple files have the same modified time (updated):

$files = array();
$mtimes = array();
$dir = new DirectoryIterator('.');
foreach($dir as $file){
  if(!$file->isFile())
    continue;

  $mtime = $file->getMTime();

  if(!$mtimes[$mtime]){
    $files[$mtime.'.0'] = $file->getFilename();
    $mtimes[$mtime] = 1;
  }else{
    $files[$mtime.'.'.$mtimes[$mtime]++] = $file->getFilename();
  }
}

ksort($files);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply