Directory Sorts on Mac and Linux?

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
hadenp
Forum Newbie
Posts: 4
Joined: Tue Jul 20, 2010 8:13 pm

Directory Sorts on Mac and Linux?

Post by hadenp »

I've written a function that lists directories. On my development environment (Mac OS X), it lists the directories in ascending order but under Linux the same code lists them in the order in which they were created.

Code: Select all

$startPath = 'documents/'; 
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($startPath), 
            RecursiveIteratorIterator::SELF_FIRST);

foreach($iterator as $file) 
 {  
    if($file->isDir()) 
    {    $fn = $file->getFilename(); 
         echo $fn;
    }
}
...
I get the same sort orders even if I use different a function to iterate through my directory tree.

Code: Select all

foreach (new DirectoryIterator('documents') as $file) 
{
    print $file->getPathname() . "<br />";
} 
Is there some other factor affecting sort order that I'm not aware of?
Thanks.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Directory Sorts on Mac and Linux?

Post by pickle »

PHP isn't actually going & getting the directory list - it's asking the operating system for the list. Apparently OS X & Linux give that list in a different order. I know glob() is subject to that difference, and it would appear DirectoryIterator() is as well.

I've never used DirectoryIterator(), so maybe there's an way to set which way it delivers the filenames - maybe a parameter to the constructor.

If not, what I would do is put the found filenames in an array, sort that array yourself, then output that sorted array.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
hadenp
Forum Newbie
Posts: 4
Joined: Tue Jul 20, 2010 8:13 pm

Re: Directory Sorts on Mac and Linux?

Post by hadenp »

Thankyou for clarifying the issue pickle.
When I run it using sort($iterator) it 'works' on OS X but Linux complains that sort expects an array.
Any idea how to sort and 'iterator' object?
Thanks!
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Directory Sorts on Mac and Linux?

Post by pickle »

Are you using the same version of PHP? Usually when the same code causes problems like that on different boxes, it's a version problem.

If that's not it - check Google. I've never used the Iterator object in this way.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply