What are the potential pitfalls of using recursion in PHP to display a tree-like structure of folders and files?

One potential pitfall of using recursion in PHP to display a tree-like structure of folders and files is the possibility of running into memory issues if the directory structure is too deep. To mitigate this, you can limit the depth of recursion or implement a way to handle large directory structures more efficiently.

function displayDirectory($dir, $depth = 0, $maxDepth = 5) {
    if ($depth > $maxDepth) {
        echo "Max depth reached";
        return;
    }
    
    $files = scandir($dir);
    
    foreach ($files as $file) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        
        echo str_repeat('-', $depth) . $file . PHP_EOL;
        
        if (is_dir($dir . '/' . $file)) {
            displayDirectory($dir . '/' . $file, $depth + 1, $maxDepth);
        }
    }
}

// Example usage
displayDirectory('/path/to/directory');