Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 500
David B Avatar asked Oct 20 '10 11:10

David B


People also ask

How do I get a list of files in a directory in PHP?

The scandir() function returns an array of files and directories of the specified directory.

How do I sort the names of files in a folder?

To sort files in a different order, click the view options button in the toolbar and choose By Name, By Size, By Type, By Modification Date, or By Access Date. As an example, if you select By Name, the files will be sorted by their names, in alphabetical order. See Ways of sorting files for other options.


1 Answers

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");
}
like image 103
codaddict Avatar answered Oct 07 '22 18:10

codaddict