The [font=monospace]glob[/font] function will (unless told otherwise) sort the directory contents alphabetically (though the ordering might not be what you want, e.g. capital letters come before lowercase letters).
As the others have said, it would also be easy to build an array of the files (using glob, scandir, a directory iterator, etc.) then sort based on whatever attribute you need to sort by.
There’s also the option of hiding everything away inside an iterator (building on the mention of SPL previously) like in this basic example.
Probably the easiest way would be to store them in an array in your existing while loop and then sort it. Then do a separate loop to echo them to the screen.
There is an easier way to get the list of contents in a directory its called the SPL library and they have a directory iterator. Sorry if this isn’t helpful. I don’t want to be a punk.
<?php
//this code is from a comment in the php manual http://www.php.net/manual/en/class.directoryiterator.php
// i haven't tried this exact piece of code
foreach (new DirectoryIterator('../moodle') as $fileInfo) {
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\
";
}
?>