What are some best practices for creating a PHP menu that dynamically displays subfolders with index images?

When creating a PHP menu that dynamically displays subfolders with index images, one best practice is to use the PHP readdir() function to scan the directory for subfolders. Then, you can iterate through the subfolders and check for the presence of an index image (such as "index.jpg" or "index.png"). Finally, you can display the subfolder name and index image in the menu.

<?php
// Specify the path to the main directory
$dir = 'path/to/main/directory';

// Open the directory
if ($handle = opendir($dir)) {
    // Read directory entries
    while (false !== ($subfolder = readdir($handle))) {
        if ($subfolder != "." && $subfolder != ".." && is_dir($dir . '/' . $subfolder)) {
            // Check for index image
            if (file_exists($dir . '/' . $subfolder . '/index.jpg')) {
                echo '<a href="' . $dir . '/' . $subfolder . '"><img src="' . $dir . '/' . $subfolder . '/index.jpg" alt="' . $subfolder . '"></a>';
            } elseif (file_exists($dir . '/' . $subfolder . '/index.png')) {
                echo '<a href="' . $dir . '/' . $subfolder . '"><img src="' . $dir . '/' . $subfolder . '/index.png" alt="' . $subfolder . '"></a>';
            } else {
                echo '<a href="' . $dir . '/' . $subfolder . '">' . $subfolder . '</a>';
            }
        }
    }
    closedir($handle);
}
?>