Php read dir and show files in alphabetical order

Can anyone tell me how to show the contents of a directory in alphabetical order?
Currently I am using the following script and it shows the files based on the date they were created.

<?php
// directory path can be either absolute or relative
$dirPath = 'docs/';

// open the specified directory and check if it's opened successfully
if ($handle = opendir($dirPath)) {

   // keep reading the directory entries 'til the end
   while (false !== ($file = readdir($handle))) {

      // just skip the reference to current and parent directory
      if ($file != "." && $file != "..") {
         if (is_dir("$dirPath/$file")) {
            // found a directory, do something with it?
            echo "[$file]<br>";
         } else {
            // found an ordinary file
          echo "<fieldset>
  <label><a href='docs/$file'>$file</label>
</fieldset>";
         }
      }
   }

   // ALWAYS remember to close what you opened
   closedir($handle);
}
?>

I’ve had a look around and found something about scan dir instead of read dir but I can’t get it to work at all.

As always any help is much appreciated.

Thanks in advance

You could store the file and dir names in an array first, and sort that.

Sounds like that would work, thanks for the super fast reply. Can you tell me how I would achieve this please? Sorry I’m not very good with arrays in php.

Check out Salathe’s SPL [URL=“http://github.com/salathe/spl-examples/wiki/Sorting-Iterators”]SortingIterator.


<?php

class SortingIterator extends ArrayIterator
{
    public function __construct(Traversable $iterator, $callback)
    {
        if ( ! is_callable($callback)) {
            throw new InvalidArgumentException(sprintf('Callback must be callable (%s given).', $callback));
        }

        parent::__construct(iterator_to_array($iterator));
        $this->uasort($callback);
    }
}

// Sort alphabetically using PHP's strnatcasecmp function
$it = new SortingIterator(new FilesystemIterator(__DIR__), 'strnatcasecmp');
foreach ($it as $file) {
    echo $file->getPathname() . PHP_EOL;
}

// Re-sort into decreasing file size order
$it->uasort(function($a,$b){ return $b->getSize() - $a->getSize(); });
foreach ($it as $file) {
    printf("%10d %s" . PHP_EOL, $file->getSize(), $file->getPathname());
}

?>

Can you tell me where in the above code do i tell it which directory to look in?

Sure, replace DIR

sorry…I’m getting errors in the above code :frowning:

Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in the following line:

public function __construct(Traversable $iterator, $callback)

any ideas?

What PHP version are you using?

PHP Version 4.4.3

Ah.

Then you’re out of luck. You could try removing the public/protected/private keywords, but I think the SPL requirements would still hinder you.

Best bet then, add the filenames to an array instead of echo’ing them out. Once you’ve collected all of them, sort and then display. As per Guido2004’s original suggestion. :stuck_out_tongue:


<?php
$array = array(
  'orange',
  'apple',
  'grapes',
  'banana',
  'pear',
  'kiwi'
);

foreach($array as $fruit){
  echo $fruit . "\
";
}

/*
  orange
  apple
  grapes
  banana
  pear
  kiwi
*/

sort($array, SORT_STRING);

foreach($array as $fruit){
  echo $fruit . "\
";
}

/*
  apple
  banana
  grapes
  kiwi
  orange
  pear
*/
?>

Upgrade.
Or tell your host to upgrade.
Or change hosting.
:slight_smile:

For what it’s worth, glob will (by default) sort the file names alphabetically and will work in your super-duper-old version of PHP.