Friday, February 11, 2011

Sort array by Alpha?

Code below takes a directory and creates an array of folder names appearing under the directory. How can order the folder names inside the array by alpha?

function get_dirs($dir) {
   $array = array();
   $d = dir($dir);
   while (false !== ($entry = $d->read())) {
       if($entry!='.' && $entry!='..') {
           $entry2 = $dir."/".$entry;
           if(is_dir($entry2)) {
               $array[] = $entry;
           }
       }
   }
   $d->close();
   return $array;
}
  • I believe sort($array); should do the trick: http://us.php.net/manual/en/function.sort.php

    From PureForm
  • You can use sort($array)

    Or rsort() if you want it in descending order.

    PureForm : This will just return the bool value from sort(). You'll have to sort the values then return them.
    Russell Dias : Oops. Good point.

0 comments:

Post a Comment