Page 1 of 1

Adding a sort order to a readdir script

Posted: Fri Oct 10, 2008 8:19 pm
by calrockx
I've got this script

Code: Select all

 
<?php
    $handle = opendir ('./');
    while (false !== ($file = readdir($handle))) {
        echo '<img src="'.$file.'"/><br />'.$file.'<br />';
    }
?>
 
 
But it doesn't spit out the images in order of filename. How can I add this? I know it involves an array, but am not sure how to write the code for it....

Re: Adding a sort order to a readdir script

Posted: Fri Oct 10, 2008 10:35 pm
by kpowell
If you want to sort the images by name, the easiest thing is to set up an array and add to it, then sort. It would look something like this:

Code: Select all

<?php
    $handle = opendir ('./');
    $img_array = array();
    while (false !== ($file = readdir($handle))) {
        $img_array[] = $file;
    }
    closedir($handle);
    sort($img_array);
    foreach($img_array as $img) {
        echo '<img src="'.$img.'"/><br />'.$img.'<br />';
    }
?>
So, you collect the file names into the array, then you sort the array. Once it's sorted, you loop through them again, echoing your original string.

Re: Adding a sort order to a readdir script

Posted: Sat Oct 11, 2008 7:41 am
by VladSun
Use glob() function.

Re: Adding a sort order to a readdir script

Posted: Mon Oct 13, 2008 3:24 am
by calrockx
kpowell, that did it...thanks!

Re: Adding a sort order to a readdir script

Posted: Mon Oct 13, 2008 2:48 pm
by VladSun
...

Code: Select all

foreach (glob("*.jpg") as $filename) {
    echo $filename;
}
Sorted!