What improvements can be made to the provided PHP code for generating a directory listing to enhance performance or readability?
The provided PHP code for generating a directory listing can be improved by using the glob function instead of scandir to retrieve files in the directory, as glob is faster and more concise. Additionally, we can separate the logic for listing directories and files into separate functions for better readability and maintainability.
<?php
function listDirectories($path) {
$directories = glob($path . '/*', GLOB_ONLYDIR);
foreach ($directories as $directory) {
echo basename($directory) . "<br>";
}
}
function listFiles($path) {
$files = glob($path . '/*');
foreach ($files as $file) {
if (!is_dir($file)) {
echo basename($file) . "<br>";
}
}
}
$path = "your_directory_path_here";
echo "Directories:<br>";
listDirectories($path);
echo "<br>Files:<br>";
listFiles($path);
?>