Sort and display directory list alphabetically using opendir() in php

You need to read your files into an array first before you can sort them. How about this?

<?php
$dirFiles = array();
// opens images folder
if ($handle = opendir('Images')) {
    while (false !== ($file = readdir($handle))) {

        // strips files extensions      
        $crap   = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-");    

        $newstring = str_replace($crap, " ", $file );   

        //asort($file, SORT_NUMERIC); - doesnt work :(

        // hides folders, writes out ul of images and thumbnails from two folders

        if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") {
            $dirFiles[] = $file;
        }
    }
    closedir($handle);
}

sort($dirFiles);
foreach($dirFiles as $file)
{
    echo "<li><a href=\"Images/$file\" class=\"thickbox\" rel=\"gallery\" title=\"$newstring\"><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\"  </a></li>\n";
}

?>

Edit: This isn’t related to what you’re asking, but you could get a more generic handling of file extensions with the pathinfo() function too. You wouldn’t need a hard-coded array of extensions then, you could remove any extension.

Leave a Comment