Page 1 of 1

Directory Sorts on Mac and Linux?

Posted: Tue Jul 20, 2010 8:37 pm
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.

Re: Directory Sorts on Mac and Linux?

Posted: Wed Jul 21, 2010 10:36 am
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.

Re: Directory Sorts on Mac and Linux?

Posted: Wed Jul 21, 2010 11:32 pm
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!

Re: Directory Sorts on Mac and Linux?

Posted: Thu Jul 22, 2010 9:58 am
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.