What are the potential pitfalls of using nested readdir functions in PHP for generating dynamic navigation?

Using nested `readdir` functions in PHP for generating dynamic navigation can lead to performance issues, as each call to `readdir` will open and read the directory contents, potentially causing unnecessary overhead. To solve this issue, it is recommended to use a recursive function to traverse the directory structure and build the navigation hierarchy.

function generateNavigation($dir) {
    $nav = '<ul>';
    
    if ($handle = opendir($dir)) {
        while (false !== ($entry = readdir($handle))) {
            if ($entry != "." && $entry != "..") {
                $fullPath = $dir . '/' . $entry;
                if (is_dir($fullPath)) {
                    $nav .= '<li>' . $entry . generateNavigation($fullPath) . '</li>';
                }
            }
        }
        closedir($handle);
    }
    
    $nav .= '</ul>';
    
    return $nav;
}

// Usage
$directory = 'path/to/directory';
echo generateNavigation($directory);