Home > Backend Development > PHP Tutorial > How Can I Sort Files by Modification Date in PHP?

How Can I Sort Files by Modification Date in PHP?

Linda Hamilton
Release: 2024-12-14 07:39:11
Original
394 people have browsed it

How Can I Sort Files by Modification Date in PHP?

Sorting Files by Date in PHP

You can acquire a list of files residing in the same directory and display their respective names and timestamps using the filemtime() function. This article provides a step-by-step guide on how to sort the output by the latest modified file.

Sorting Algorithm Using Globbing and usort()

To retrieve all files with a specific extension within a specified path, you can employ the glob() function. Once you have the array of files, use the usort() function to organize them based on their modification timestamp.

$files = glob('path/to/files/*.swf');
usort($files, function($a, $b) {
    return filemtime($b) - filemtime($a);
});
Copy after login

Alternative Sorting Method Using array_multisort()

An alternative approach involves utilizing the array_multisort() function along with the filemtime() function to sort the file array based on timestamps.

$files = array_merge(glob('path/to/files/*.swf'), glob('path/to/files/*.jpg'));
array_multisort(array_map('filemtime', $files), SORT_DESC, $files);
Copy after login

Looping Through the Sorted Files

Subsequently, you can iterate over the sorted array to display the file information, including names and timestamps.

foreach ($files as $file) {
    echo "$file - " . date('F d Y, H:i:s', filemtime($file)) . "<br>";
}
Copy after login

By implementing these sorting techniques, you can organize your files effectively based on their modification dates.

The above is the detailed content of How Can I Sort Files by Modification Date in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template