How can filenames be sorted alphabetically when using readdir() to read directories in PHP?

When using readdir() to read directories in PHP, the filenames may not be sorted alphabetically by default. To sort the filenames alphabetically, you can store the filenames in an array, use the sort() function to sort the array, and then iterate over the sorted array to process the files in alphabetical order.

$dir = "/path/to/directory";
$files = array();

if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $files[] = $file;
        }
    }
    closedir($handle);
}

sort($files);

foreach ($files as $file) {
    echo $file . "<br>";
}