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

How to Sort Files by Modification Date in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 08:47:09118browse

How to Sort Files by Modification Date in PHP?

Sorting Files by Date in PHP

Sorting files by their modification date in PHP can be achieved through various techniques. One approach is to utilize the glob() method to retrieve a list of files within a specified directory and then use the usort() function to arrange these files based on their modification time.

Method:

The following code snippet demonstrates how to sort files by date in PHP:

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

foreach($files as $file){
    printf('<tr'><td'><input type="checkbox" name="box[]"></td>
            <td><a href="%1$s" target="_blank">%1$s</a></td>
            <td>%2$s</td></tr>', 
            $file, // or basename($file) for just the filename w\out path
            date('F d Y, H:i:s', filemtime($file)));
}

In this code:

  1. The glob() function retrieves a list of files with the .swf extension within the specified directory.
  2. The usort() function sorts the files using an anonymous callback function that subtracts the modification time of file a from the modification time of file b. This results in files being arranged in descending order of modification time, with the latest modified file at the beginning of the array.
  3. The foreach loop iterates through the sorted files and displays their names, links, and modification dates.

This method provides a simple and efficient way to sort files by date in PHP, allowing you to easily retrieve and display the latest modified files.

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

Statement:
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