Page 1 of 1

I know there is a better way to do this.

Posted: Thu Jul 21, 2005 8:50 am
by aphexjesus
Hi. I am new to php programming, and i need a way to select the last file in the directory. (actually, i would like to select the newest/most recent file, but i got this working first.) Here is how i did, but i know there has to be a much more elegant way to do so... any suggestions are very appreciated.

Code: Select all

<?php
$filelist = array();
$x=0;
if ($handle = opendir('./coupons')) {
   while (false !== ($file = readdir($handle))) {
       if ($file != "." && $file != "..") {
           $filelist[$x] = $file;
           $x++;
       }
   }
   echo end($filelist);
   closedir($handle);
}
?>

Posted: Thu Jul 21, 2005 9:12 am
by Chris Corbyn
Actually if you want to get the newest file you will unfortunately need to loop over all files like you are doing.

There's a better way to get the newest however...

Code: Select all

function get_newest_file($dir) { //$dir requires the trailing slash

    $stack = array();
    $handle = opendir($dir);
    while ($file = readdir($handle)) {

        if ($file != "." && $file != "..") {

            //Get the timestamp of "last modified" date
            $last_modified = filemtime($dir.$file); 
            $stack[$file] = $last_modified; //Add to stack

        } //End if

    } //End while
    closedir($handle);

    rsort($stack, SORT_NUMERIC); //Reverse sort the array numerically
    return $stack[0];

}

Posted: Thu Jul 21, 2005 10:27 am
by Burrito
if you use glob() without the NO_SORT flag, it will create an array and sort them by the date they were created. You could then array_pop() the array to get the file you want.