Sort Files Alphabetically

Hi,

How do I list files alphabetically?

Thanks.


$current_dir = 'documents/';
          if ($handle = opendir($current_dir)) {
              while (false !== ($file = readdir($handle))) {
                  if ($file != "." && $file != "..") {
$currentfile = $current_dir.urlencode($file);		
echo $currentfile;
 echo '<li><a href='.$currentfile.'>'.$file.'</a></li>';
                  }
              }
              closedir($handle);
          }	

Exactly. :slight_smile:

As you iterate the directory (using your preferred method, mine’s SPL), store the filenames in an array. Once complete, sort, display.

Good call ‘Cute Tink’.

Hi,
Thanks.The below works well.

$current_dir = 'documents/';
          if ($handle = opendir($current_dir)) 
					{
					 	  $i=0;
              while (false !== ($file = readdir($handle))) 
							{
                  if ($file != "." && $file != "..") 
									{
									 	 $files[$i] = $file;
										 $i++;
                  }
              }
              closedir($handle);
          }	
					sort($files);
					
          for($i=0; $i<sizeof($files); $i++)
          {
           				$currentfile = $current_dir.rawurlencode($files[$i]);		
          				//echo $currentfile;
                  echo '<li><a href='.$currentfile.'>'.$files[$i].'</a></li>';
          }

The [font=monospace]glob[/font] function will (unless told otherwise) sort the directory contents alphabetically (though the ordering might not be what you want, e.g. capital letters come before lowercase letters).

As the others have said, it would also be easy to build an array of the files (using glob, scandir, a directory iterator, etc.) then sort based on whatever attribute you need to sort by.

There’s also the option of hiding everything away inside an iterator (building on the mention of SPL previously) like in this basic example.

Probably the easiest way would be to store them in an array in your existing while loop and then sort it. Then do a separate loop to echo them to the screen.

http://php.net/manual/en/function.scandir.php

There is an easier way to get the list of contents in a directory its called the SPL library and they have a directory iterator. Sorry if this isn’t helpful. I don’t want to be a punk.



<?php
//this code is from a comment in the php manual http://www.php.net/manual/en/class.directoryiterator.php
// i haven't tried this exact piece of code
foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\
";
}

?>