Sometimes, we want to sort files by date in PHP.
In this article, we’ll look at how to sort files by date in PHP.
How to sort files by date in PHP?
To sort files by date in PHP, we can use the filemtime
and usort
functions.
For instance, we write
$files = glob("path/to/files/*.swf");
usort($files, function ($a, $b) {
return filemtime($b) - filemtime($a);
});
to get the files with the swf extension with glob
in the path/to/files folder.
Then we call usort
to sort the $files
by the file date with a function that gets the time of each file and compare them.
We get the file date with filemtime
and then sort them in descending order with
filemtime($b) - filemtime($a)
The $files
array is then sorted in place.
Conclusion
To sort files by date in PHP, we can use the filemtime
and usort
functions.