Link to home
Start Free TrialLog in
Avatar of hankknight
hankknightFlag for Canada

asked on

PHP readdir(): Sort results alphanumerically

I use the attached code to return a list of directories.  How can I display the results sorted alphanumerically?
if ($handle = opendir('directory')) {
    while (($file = readdir($handle)) !==false) {
        if (substr($file,0,1) != "." && is_dir($file)) {
	echo $file;
        }
    }
    closedir($handle);
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of ludofulop
ludofulop

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@ludofulop: Proof that great minds think alike!  ;-)

~Ray
@hankknight: Here is a man page worth reading as you choose the exact kind of sort you need.

http://us.php.net/manual/en/array.sorting.php
I think ksort may be better?
<?php
$directory = new directoryListing("../testfolder");
print_r($directory->sortListing());

class directoryListing {
   private $_dPath;
   private $_listing = array();
   public function __construct($path) {
      $this->_dPath = $path;
   }
   private function getListing() {
      if ($handle = opendir($this->_dPath)) {
         while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != ".." && !is_dir($file)) {
               $this->_listing[] = $file;
            }
         }
         closedir($handle);
      }
   }
   public function sortListing()
   {
      $this->getListing();
      ksort($this->_listing);
      return $this->_listing;      
   }
}
?>

Open in new window

Please see:
http://us3.php.net/manual/en/function.ksort.php

There are only numbered keys in the arrays we built here, so the sort order with ksort will not change.
Hi Ray,

Sorry, sort does work fine, it must of been the folder structure I was testing it on, one thing I did find was wrong in the previous examples was that  is_dir($file)  needs to be ! is_dir($file)  as it was not returning any listings.

Darren
I think the OP wanted to sort a list of directories.  That is probably why we found is_dir() in his original post.
Yep, know that , that what the class returns...
Avatar of hankknight

ASKER

Thanks