Adding a sort order to a readdir script

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
calrockx
Forum Newbie
Posts: 6
Joined: Mon Apr 28, 2008 11:32 am

Adding a sort order to a readdir script

Post 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....
kpowell
Forum Newbie
Posts: 6
Joined: Thu Oct 09, 2008 4:11 pm

Re: Adding a sort order to a readdir script

Post 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.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Adding a sort order to a readdir script

Post by VladSun »

Use glob() function.
There are 10 types of people in this world, those who understand binary and those who don't
calrockx
Forum Newbie
Posts: 6
Joined: Mon Apr 28, 2008 11:32 am

Re: Adding a sort order to a readdir script

Post by calrockx »

kpowell, that did it...thanks!
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Adding a sort order to a readdir script

Post by VladSun »

...

Code: Select all

foreach (glob("*.jpg") as $filename) {
    echo $filename;
}
Sorted!
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply