How do I sort a directory listing alphabetically using `opendir()` in PHP?

Mary-Kate Olsen
Release: 2024-10-27 17:47:01
Original
184 people have browsed it

How do I sort a directory listing alphabetically using `opendir()` in PHP?

Alphabetically Sorting Directory Listings with opendir() in PHP

To sort a directory listing alphabetically using opendir() in PHP, follow these steps:

  1. Gather Files into an Array: Before sorting, read all files into an array using $dirFiles = array();, similar to this:
<code class="php">$dirFiles = array();
while (false !== ($file = readdir($handle))) {
    $dirFiles[] = $file;
}</code>
Copy after login
  1. Sort the Array: Once the files are in the array, you can sort them alphabetically using sort():
<code class="php">sort($dirFiles);</code>
Copy after login
  1. Display the Sorted Listings: Finally, iterate over the sorted $dirFiles array and display the images and thumbnails as before:
<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>
Copy after login

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 != "." &amp;&amp; $file != ".." &amp;&amp; $file != "index.php" &amp;&amp; $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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!