PHP (folder) File Listing in Alphabetical Order?

SoulieBaby picture SoulieBaby · Jul 8, 2009 · Viewed 11.3k times · Source

I'm not sure how simple this would be, but I'm using a script which displays the files from a specific folder, however I'd like them to be displayed in alphabetical order, would it be hard to do this? Here's the code I'm using:

if ($handle = opendir($mainframe->getCfg( 'absolute_path' ) ."/images/store/")) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..")  {
                if (($file != "index.html")&&($file != "index.php")&&($file != "Thumbs.db")) {
                $strExt = end(explode(".", $file));
                    if ($strExt == 'jpg') {
                        $Link = 'index.php?option=com_shop&task=deleteFile&file[]='.$file;
                        $thelist .= '<tr class="row0"><td nowrap="nowrap"><a href="'.$Link.'">'.$file.'</a></td>'."\n";
                        $thelist .= '<td align="center" class="order"><a href="'.$Link.'" title="delete"><img src="/administrator/images/publish_x.png" width="16" height="16" alt="delete"></a></td></tr>'."\n";
                    }

                }
            }
        }
        closedir($handle); 
    }   
    echo $thelist;

:)

Answer

Christian Hang-Hicks picture Christian Hang-Hicks · Jul 8, 2009

Instead of using readdir you could simply use scandir (documentation) which sorts alphabetically by default.

The return value of scandir is an array instead of a string, so your code would have to be adjusted slightly, to iterate over the array instead of checking for the final null return value. Also, scandir takes a string with the directory path instead of a file handle as input, the new version would look something like this:

foreach(scandir($mainframe->getCfg( 'absolute_path' ) ."/images/store/") as $file) {
  // rest of the loop could remain unchanged
}