How can a FilterIterator be used to improve the efficiency of searching for files in PHP?

When searching for files in PHP, it can be inefficient to loop through all files in a directory and then apply filtering conditions. Using a FilterIterator can improve efficiency by allowing us to define filtering conditions upfront and iterate through only the files that meet those conditions.

// Define a custom FilterIterator to filter files based on specific conditions
class CustomFilterIterator extends FilterIterator {
    public function accept() {
        // Define your filtering conditions here
        return $this->isFile() && $this->getExtension() === 'txt';
    }
}

// Create a DirectoryIterator for the target directory
$directory = new DirectoryIterator('/path/to/directory');

// Create an instance of the custom FilterIterator
$filterIterator = new CustomFilterIterator($directory);

// Iterate through the filtered files
foreach ($filterIterator as $file) {
    echo $file->getPathname() . PHP_EOL;
}