How can I list all files in a directory sorted alphabetically using PHP?

David B picture David B · Oct 20, 2010 · Viewed 44.7k times · Source

I'm using the following PHP code to list all files and folders under the current directory:

<?php
    $dirname = ".";
    $dir = opendir($dirname);

    while(false != ($file = readdir($dir)))
        {
          if(($file != ".") and ($file != "..") and ($file != "index.php"))
             {
              echo("<a href='$file'>$file</a> <br />");
        }
    }
?>

The problem is list is not ordered alphabetically (perhaps it's sorted by creation date? I'm not sure).

How can I make sure it's sorted alphabetically?

Answer

codaddict picture codaddict · Oct 20, 2010

The manual clearly says that:

readdir
Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

What you can do is store the files in an array, sort it and then print it's contents as:

$files = array();
$dir = opendir('.'); // open the cwd..also do an err check.
while(false != ($file = readdir($dir))) {
        if(($file != ".") and ($file != "..") and ($file != "index.php")) {
                $files[] = $file; // put in array.
        }   
}

natsort($files); // sort.

// print.
foreach($files as $file) {
        echo("<a href='$file'>$file</a> <br />\n");
}