tags:

views:

1270

answers:

4

I am using the code below to display all the files from a directory in a drop down menu. Does anyone know how to make this alphabetical? I presume it has something to do with the sort function, I just can't figure out how!

<?php
$dirname = "images/";
$images = scandir($dirname);
$dh = opendir($dirname);

while ($file = readdir($dh)) {
if (substr($file, -4) == ".gif") {
print "<option value='$file'>$file</option>\n"; }
}
closedir($dh);
?>
+5  A: 

Why are you reading all the filenames using scandir() and then looping through them with the readdir() method? You could just do this:

<?php

$dirname = "images/";
$images = scandir($dirname);

// This is how you sort an array, see http://php.net/sort
sort($images);

// There's no need to use a directory handler, just loop through your $images array.
foreach ($images as $file) {
    if (substr($file, -4) == ".gif") {
        print "<option value='$file'>$file</option>\n"; }
    }
}

?>

Also you might want to use natsort(), which works the same way as sort() but sorts in "natural order". (Instead of sorting as 1,10,2,20 it will sort as 1,2,10,20.)

yjerem
+2  A: 

scandir

array scandir ( string $directory [, int $sorting_order [, resource $context ]] )

Returns an array of files and directories from the directory . Parameters

directory The directory that will be scanned.

sorting_order By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is used (set to 1), then the sort order is alphabetical in descending order.

William Macdonald
+1  A: 
$matches = glob("*.gif");
if ( is_array ( $matches ) ) {
   sort($matches);
   foreach ( $matches as $filename) {
      echo '<option value="'.$filename.'">.$filename . "</option>";
   }
}
A: 

As William Macdonald pointed out here scandir() will in fact sort the returning array according to its $sorting_order parameter (or its default: "By default, the sorted order is alphabetical in ascending order."). The problem with your code is, that you generate the array of files in your directory using $images = scandir($dirname); but you do not use the returned array in your code further on. Instead you iterate over the directory contents using another method:

$dh = opendir($dirname);
while ($file = readdir($dh)) {
    if (substr($file, -4) == ".gif") {
        print "<option value='$file'>$file</option>\n"; 
    }
}
closedir($dh);

This is why your result is not sorted.

Stefan Gehrig