How can PHP functions be structured to handle recursive directory searches efficiently?

To handle recursive directory searches efficiently in PHP, we can use a function that utilizes a recursive approach to traverse through directories and subdirectories. This function should be designed to handle large directory structures without causing memory issues by using iterators or generators to process files one by one instead of loading all file paths into memory at once.

function searchDirectories($dir){
    $files = scandir($dir);
    
    foreach($files as $file){
        if ($file != '.' && $file != '..'){
            $path = $dir . '/' . $file;
            if (is_dir($path)){
                searchDirectories($path);
            } else {
                echo $path . "\n";
            }
        }
    }
}

searchDirectories('/path/to/directory');