mudraya katusha
mudraya katusha

Reputation: 171

how to sort directories and files in a certain directory?

I am reading all the directories and files inside a directory and want to sort the files alphabetically.

if ($handle = opendir($dir)) {
   while (false !== ($file = readdir($handle))) {
      $files = array($file);
      sort($files);

      $clength = count($files);
      for($x = 0; $x < $clength; $x++) {
        echo $files[$x];
        echo "<br>";
      }

Code above outputs me all the directories and files but does not sort them alphabetically. What I am doing wrong?

Upvotes: 0

Views: 51

Answers (2)

nice_dev
nice_dev

Reputation: 17805

To answer your question, you need to first collect all the files and then sort them at once. So your code would look like-

<?php

while (false !== ($file = readdir($handle))) {
      $files[] = $file;
}

sort($files);
  • But, a better options is to just use scandir() which returns you a list of files(including folders) in your directory and then you could sort them accordingly.

  • I have used usort() which sort files in alphabetical order ignoring upper case or lower case while preserving the original representation of the file name.

Code:

<?php 

$files = array_diff(scandir(YOUR_DIRECTORY_PATH_HERE),array(".",".."));

usort($files,function($file1,$file2){
    return strcmp(strtolower($file1),strtolower($file2));
});

print_r($files);
  • I have used array_diff() to remove the . and .. which is included in the result of scandir().

Upvotes: 3

Black Flag
Black Flag

Reputation: 889

You must use this one.

if ($handle = opendir($dir)) {


        while (false !== ($file = readdir($handle))) {
            $files[] = $file;

        }
        sort($files);
        $clength = count($files);
        for ($x = 0; $x < $clength; $x++) {
            echo $files[$x];
            echo "<br>";
        }
    }

Update

$files[] = strtolower($file); // for ignore first letter capital

Upvotes: 2

Related Questions