Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP readdir() not returning files in alphabetical order

Tags:

php

I am reading through a directory with some pictures and such using a pretty simple implementation of readdir() like the following:

if ($handle = opendir($path)) {
    while (false !== ($szFilename = readdir($handle))) {
    if ($szFilename[0] !== '.') {
        if (is_file($path.$szFilename)) {
                // do stuff
            }
        }
     }
 }

The problem that I am having is that the files are not being read in alphabetical order as the docs for readdir() state:

Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

Another weird thing is that, on the local testing server, the same code works great. This is running on a server using the LAMP stack in both cases.

I know that I can build an array and just sort it, but I was wondering if I was missing something in what I was doing.

like image 484
Buggabill Avatar asked Feb 12 '09 14:02

Buggabill


2 Answers

Alphabetical order :: I think you misread the snippet you quoted...

Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem.

The fact that 'ls' would display the files in (usually) alphabetical order does not mean that's how they are stored on the filesystem. PHP is behaving as spec, I'm afraid.

You may want to consider using scandir as the basis for your efforts, if alphabetical sorting is a must. :)

like image 182
ZombieSheep Avatar answered Sep 20 '22 05:09

ZombieSheep


You could copy all the filenames into an array and then use

<?php
sort($filesArray);
?>
like image 45
alex Avatar answered Sep 19 '22 05:09

alex