How does PHP readdir/opendir sort

1.1k views Asked by At

I wondered how come that when calling following code the file(name)s in the array are always sorted differently. How does PHP opendir sort the files and how can I change it in the system without having to put it inside an array first which I then sort?

$dh  = opendir($dir);  
    do {
        $files_in_dir[] = $filename;
    }
    while (false !== ($filename = readdir($dh)));
2

There are 2 answers

0
Valera Leontyev On BEST ANSWER

The entries are returned in the order in which they are stored by the filesystem.

http://php.net/manual/en/function.readdir.php

0
Ali MasudianPour On

As a suggestion, use PHP's scandir() function instead, as PHP's official document defines it:

scandir — List files and directories inside the specified path

And also supports sorting.

By default, the sorted order is alphabetical in ascending order. If the optional sorting_order is set to SCANDIR_SORT_DESCENDING, then the sort order is alphabetical in descending order. If it is set to SCANDIR_SORT_NONE then the result is unsorted.