Deproblemify
Deproblemify

Reputation: 3430

How does PHP readdir/opendir sort

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)));

Upvotes: 1

Views: 1241

Answers (2)

Valera Leontyev
Valera Leontyev

Reputation: 1181

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

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

Upvotes: 1

Ali MasudianPour
Ali MasudianPour

Reputation: 14459

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.

Upvotes: 1

Related Questions