PHP Sort Listing of Files in Directory

I created a page that, using PHP, listed files contained in a directory.  However, the listing wasn't as user friendly as it could be because the file list wasn't sorted.  So here is how I got a list of files in a directory to be sorted by name.

BEFORE (NO SORT)

This method just uses the opendir function, which outputs the objects in a directory according to how the computer indexes them, so it's not sorted.

$count = "0";

$dir = opendir("data");
    while($list = readdir($dir))
    {   
        if ($list[0] != "." && $list[0] != ".." )
       {
                echo "$list";
        $count++;
        }
    }

AFTER (WITH SORT)

Here, the contents are placed into an array, which can in turn be sorted.

// read directory into array
$handle = opendir("data"); 
$dir_array = array();
while($file = readdir($handle))
    if(is_file("data/$file"))
    { 
        $dir_array[] = $file;
    } 
closedir($handle);

// sort the array
sort($dir_array); 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.