Well, we're going to have to take a slightly different approach. Here you open a directory handle and then iterate over the files. If we want to sort the directory list then this needs to be done first before iterating over. Let's hide the details in a function so that we can use it again in the future.
function filesByDate( $directory ) {
}
First off we need to get all the files in the directory, and set up an array which will ultimately hold the sorted directory listing.
function filesByDate( $directory ) {
$files = array();
if( !$dh = opendir( $directory ) ) {
trigger_error( "Failed to open directory [" . $directory . "]", E_USER_WARNING );
return false;
}
while( ($file = readdir( $directory )) !== false ) {
$files[] = $file;
}
return $files;
}
This just returns an array of files in the order that readdir gives them to us. The next step is to figure out a way of sorting the files by their date. To do this we'll use the concept of an associative array using the filename for the key and the date for the value, afterwards we'll do a key preserving sort and then grab the sorted set of keys (the filenames) and return them.
function filesByDate( $directory ) {
$files = array();
if( !$dh = opendir( $directory ) ) {
trigger_error( "Failed to open directory [" . $directory . "]", E_USER_WARNING );
return false;
}
while( ($file = readdir( $directory )) !== false ) {
$files[$file] = fileatime( $directory . DIRECTORY_SEPARATOR . $file );
}
asort( $files );
return array_keys( $files );
}