In what scenarios would filtering files be more efficient than sorting them in a PHP script?

Filtering files would be more efficient than sorting them in a PHP script when you only need to work with a subset of files that meet certain criteria. For example, if you only need to process files that have a specific file extension or files that were modified within a certain time frame, filtering would be the better approach. This can help reduce the amount of data that needs to be processed, leading to faster execution times.

<?php
$directory = '/path/to/directory';

// Filter files by file extension
$files = array_filter(scandir($directory), function($file) {
    return pathinfo($file, PATHINFO_EXTENSION) == 'txt';
});

// Process the filtered files
foreach ($files as $file) {
    // Do something with the file
}
?>