Alphabetically Sorting Directory Listings with opendir() in PHP
To sort a directory listing alphabetically using opendir() in PHP, follow these steps:
<code class="php">$dirFiles = array(); while (false !== ($file = readdir($handle))) { $dirFiles[] = $file; }</code>
<code class="php">sort($dirFiles);</code>
<code class="php">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>
Here's a modified script that incorporates these steps:
<code class="php">... (unchanged code) ... // Read files into an array $dirFiles = array(); while (false !== ($file = readdir($handle))) { if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") { $dirFiles[] = $file; } } closedir($handle); // Sort the array sort($dirFiles); // Display the sorted listings 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>
The above is the detailed content of How do I sort a directory listing alphabetically using `opendir()` in PHP?. For more information, please follow other related articles on the PHP Chinese website!