I know there is a better way to do this.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aphexjesus
Forum Newbie
Posts: 1
Joined: Thu Jul 21, 2005 8:44 am

I know there is a better way to do this.

Post 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);
}
?>
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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];

}
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post 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.
Post Reply