When working with directory contents, sometimes it's useful to list the files by age, either newest or oldest first. For example, you might want to display the 10 most recently uploaded photos in a directory, or delete the oldest files from a temp directory. PHP provides an easy way to get a directory's file listing, scandir(), but it sorts the file list alphabetically. What if you'd rather sort by date?
To build a date-ordered file list, it's necessary to read the directory contents manually with
readdir(). As each file is discovered, it can be added to an array using its modification time as the array key. Finally, the resulting array can be sorted (or reverse-sorted) by key, producing a list of files that's ordered by date, from oldest to newest (or vice versa).
Here's a function,
scandir_chrono(), that implements this logic with a few extra features:
/** * Return an array of file paths representing the contents of the target * directo...