How can recursion be utilized in PHP to search through directories and their subdirectories effectively?

When searching through directories and their subdirectories in PHP, recursion can be utilized effectively by creating a function that calls itself to traverse each directory and its contents. This allows for a flexible and scalable approach to searching through nested directories without the need for complex loops or nested code structures.

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

$searchDir = 'path/to/your/directory';
searchDirectories($searchDir);