Home > Article > Backend Development > How can I sort directory listings alphabetically using the opendir() function in PHP?
Sorting Directory Listings Alphabetically with opendir() in PHP
Sorting a directory listing alphabetically can be achieved using PHP's opendir() function. Here's a modified version of the provided code:
<code class="php"><?php // Open the images folder $dirFiles = array(); if ($handle = opendir('Images')) { while (false !== ($file = readdir($handle))) { // Strip file extensions and remove unnecessary characters $crap = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-"); $newstring = str_replace($crap, " ", $file); // Hide folders and add files to an array if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") { $dirFiles[] = $file; } } closedir($handle); } // Sort the file array alphabetically sort($dirFiles); // Display the sorted list of images and thumbnails 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"; } ?></code>
Explanation:
The above is the detailed content of How can I sort directory listings alphabetically using the opendir() function in PHP?. For more information, please follow other related articles on the PHP Chinese website!