0

I search a director with glob function and get the matched files' list. Then by checking filemtime of the files I create a map. Then sort the map with respect to file dates. At last I get latest file's name and modification time. My code is like this. It works well for small directories, but it's slow for big directories. I wonder whether is there a faster/clever way?

$fileList = array();
// $id = is the argument of this function
$files = glob('myfolder'.DS.'someone'.$id.'*.txt');
if (empty($files)) {
    return 0;
}
foreach ($files as $file) {
    $fileList[filemtime($file)] = $file;
}

if (sizeof($files) > 1) {
    ksort($fileList);
}

$latestFilename = end($fileList);
$fileLastModifDate = filemtime( $latestFilename );
trante
  • 33,518
  • 47
  • 192
  • 272
  • This question (http://stackoverflow.com/questions/124958/glob-sort-by-date) gives various possiblities (esp the link in the first comment which has some very clever ideas). You would probably have to benchmark each yourself to determine which was the fastest. – Rob Johnstone May 18 '13 at 20:35
  • Do you only need to know which file is the last modified? If so, building a list and sorting it is not required. – Reactgular May 18 '13 at 21:18
  • Possible duplicate: http://stackoverflow.com/questions/5448374/get-last-modified-file-in-a-dir – Reactgular May 18 '13 at 21:18

1 Answers1

0

i suspect that your "mapping" is actually creating a hash table, and then the sort is not efficiant as one might expect, i would try this: (this is the basic, u can fancy it up)

class file_data
{
   public  $time; // or whatever u use
   public $file;
}

$arr =new array ();
foreach ($files as $file) {
     $new_file = new file_data ();
     $file_data->time = filetime($file);
     $file_data->file = $file;   
     array_push ($arr,$file_data);
}

function file_object_compare ($a,$b)
{
    if ($a->time > $b->time) return -1;
//    etc... i.e 0 eual 1 otherwise

}

//and then u sort
usort ($arr,"file_object_compare");

// or // and this is probably better, if u only need this paricular sorting

function file_object_compare ($a,$b)
{
    if (filetime($a)> filetime($b)) return -1;
//    etc... i.e 0 eual 1 otherwise    
}

usort ($files,"file_object_compare");
yaron
  • 1,283
  • 1
  • 11
  • 21