How can recursion be effectively used to read directory structures in PHP?

When reading directory structures in PHP, recursion can be effectively used to traverse nested directories and list all files and subdirectories within them. By recursively calling a function to handle each directory encountered, we can efficiently read the entire directory structure.

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

// Call the function with the root directory
readDirectory('/path/to/directory');