How can PHP file system functions be optimized for efficient menu generation from directory files?

To optimize PHP file system functions for efficient menu generation from directory files, we can use the opendir() function to open a directory, iterate through its contents using readdir(), filter out any unwanted files, and then generate a menu based on the remaining files.

$dir = "path/to/directory";

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        echo '<ul>';
        while (($file = readdir($dh)) !== false) {
            if ($file != '.' && $file != '..' && !is_dir($dir . '/' . $file)) {
                echo '<li><a href="' . $file . '">' . $file . '</a></li>';
            }
        }
        echo '</ul>';
        closedir($dh);
    }
}