What are the alternative methods to using the glob function in PHP for retrieving and sorting files based on specific criteria?

The glob function in PHP can be limited in its capabilities for retrieving and sorting files based on specific criteria. An alternative method is to use the DirectoryIterator class, which allows for more flexibility in filtering and sorting files. By using DirectoryIterator, you can easily iterate over files in a directory, apply custom filters, and sort them based on various criteria.

// Using DirectoryIterator to retrieve and sort files based on specific criteria
$directory = '/path/to/directory';
$files = [];

$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileInfo) {
    if ($fileInfo->isFile() && $fileInfo->getExtension() === 'txt') {
        $files[$fileInfo->getFilename()] = $fileInfo->getMTime();
    }
}

asort($files); // Sort files by modification time

foreach ($files as $filename => $mtime) {
    echo $filename . ' - Last modified: ' . date('Y-m-d H:i:s', $mtime) . PHP_EOL;
}