READDIR: Why is the ordering messed up?

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
figmented
Forum Newbie
Posts: 6
Joined: Mon Jul 07, 2008 6:38 pm

READDIR: Why is the ordering messed up?

Post by figmented »

Does anyone have any idea why the READDIR function would read a directory in random order like this?

Code: Select all

Resource id #2
 
Files:
 
7.jpg
6_thumb.jpg
.
..
3.jpg
3_thumb.jpg
2_thumb.jpg
0.jpg
5_thumb.jpg
1_thumb.jpg
1.jpg
4_thumb.jpg
8_thumb.jpg
0_thumb.jpg
5.jpg
4.jpg
8.jpg
6.jpg
2.jpg
7_thumb.jpg
I know it's NOT arranged by date, size, etc. Also, the DIR and LS commands lists the images in correct order like this:

Code: Select all

0.jpg        1_thumb.jpg  3.jpg        4_thumb.jpg  6.jpg        7_thumb.jpg
0_thumb.jpg  2.jpg        3_thumb.jpg  5.jpg        6_thumb.jpg  8.jpg
1.jpg        2_thumb.jpg  4.jpg        5_thumb.jpg  7.jpg        8_thumb.jpg
 
I'm using the sample code found here.

Code: Select all

<?
if ($handle = opendir('img/photos/people/')) {
    echo "$handle<br /><br />";
    echo "Files:<br /><br />";
 
    while (false !== ($file = readdir($handle))) {
        echo "$file<br />";
    }
 
    closedir($handle);
}
?>
I don't experience the problem on another server. I'm using PHP5 in both cases, and I can't think of any differences. Can somebody point me in the right direction? Thanks!
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: READDIR: Why is the ordering messed up?

Post by Benjamin »

It's reading them in the order of the inodes. The php manual entry for readdir states:
The filenames are returned in the order in which they are stored by the filesystem.
You can enter them into an array and use the sorting functions to change the order as you require.
Post Reply