In PHP, how can efficient filtering of files and folders be achieved before the actual iteration process to optimize performance?

When filtering files and folders in PHP, it is important to efficiently exclude unwanted items before iterating over them to optimize performance. This can be achieved by using functions like `is_file()` and `is_dir()` to quickly determine if an item is a file or a folder, and applying additional filters based on file extensions or folder names before processing them.

$directory = '/path/to/directory';

$files = scandir($directory);

foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
        $fullPath = $directory . '/' . $file;
        
        if (is_file($fullPath) && pathinfo($fullPath, PATHINFO_EXTENSION) == 'txt') {
            // Process the file
            echo $file . "\n";
        } elseif (is_dir($fullPath) && $file != 'exclude_folder') {
            // Recursively process the folder
            echo $file . "\n";
        }
    }
}