How to sort files by date in PHP
Your current script correctly retrieves file modification timestamps using filemtime() and formats them for display. However, it iterates through the directory entries sequentially based on the order returned by readdir(). This order is often arbitrary or filesystem-dependent, meaning your output will not necessarily reflect chronological sorting. To display the latest modified file first, you need to leverage PHP's built-in sorting capabilities before rendering the data.
The most straightforward approach involves collecting the relevant data into an array and then applying a sort function. In your specific case, you are filtering for .swf files. A robust solution requires separating the data retrieval from the presentation logic. You should iterate through the directory, validate the file extension, and immediately push a structured object or associative array into a master list instead of echoing directly inside the loop.
Here is how you can refactor your code to achieve sorted output:
$handle = opendir('.');
$fileList = [];
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
// Check for the specific extension first
if (strpos($file, ".swf") === strlen($file) - 4) {
$filePath = realpath("./$file");
// Use filemtime to get the timestamp and format it
$lastModified = date('F d Y, H:i:s', filemtime($filePath));
$fileList[] = [
'name' => $file,
'date' => $lastModified,
'timestamp' => filemtime($filePath) // Keep raw timestamp for sorting logic if needed
];
}
}
}
closedir($handle);
// Sort the array by modification time in descending order (newest first)
usort($fileList, function ($a, $b) {
return $b['timestamp'] <=> $a['timestamp'];
});
foreach ($fileList as $item) {
echo "$item[name] - {$item[date]}" . PHP_EOL;
}
This refactoring introduces a few critical improvements. First, by storing the raw filemtime timestamp alongside the formatted date string, you enable precise numeric comparison using the spaceship operator (<=>). String-based sorting on formatted dates (e.g., "January 1st" vs "February 2nd") can be error-prone and locale-dependent; sorting integers is reliable across all environments. Second, separating the logic into distinct phasesâcollection, sorting, and renderingâmakes the code easier to maintain. If you ever need to change the output format or add metadata later, it won't break your sort logic.
There are trade-offs to consider regarding performance and file system interactions. The readdir() function does not guarantee any specific order in older PHP versions or certain operating systems like Windows. Relying on this behavior is a common pitfall that leads to inconsistent results. Additionally, calling filemtime() inside the loop for every single file entry is slightly less efficient than checking the extension first, though modern filesystems handle metadata reads quickly enough that this rarely becomes a bottleneck unless you are processing thousands of files in a tight loop.
If you prefer not to iterate manually, PHP provides helper functions like scandir() which return entries in natural order by default, but sorting is still required for chronological results. For large-scale applications where performance is critical, consider caching the modification timestamps in memory if you are processing the same directory repeatedly within a single request lifecycle.
For developers working within the Laravel ecosystem, this pattern integrates seamlessly with filesystem managers. While raw PHP code works well for simple scripts, Laravel often abstracts file operations using Storage::disk('local')->files() combined with sorting queries if your files were uploaded via the framework. However, for direct directory scanning as shown in your example, native PHP functions remain the most efficient and dependency-free solution.