gatzkerob
gatzkerob

Reputation: 899

PHP (WAMP) not sorting files the same way as Windows

Using WAMP, I'm trying to make PHP sort the same way as Windows using the following code:

<?php
    $folder = opendir("folderx");
    $fileNameList = array();

    while(false !== ($fileName = readdir($folder))){
        array_push($fileNameList, $fileName);
    }

    echo "<pre>";
    print_r($fileNameList);
    echo "</pre>";
?>

However, I'm getting weird results. This is how PHP is sorting:

Array
(
[0] => .
[1] => ..
[2] => New Text Document - Copy (2) - Copy - Copy.txt
[3] => New Text Document - Copy (2) - Copy.txt
[4] => New Text Document - Copy (2).txt
[5] => New Text Document - Copy (3) - Copy.txt
[6] => New Text Document - Copy (3).txt
[7] => New Text Document - Copy (4) - Copy.txt
[8] => New Text Document - Copy (4).txt
[9] => New Text Document - Copy - Copy (2) - Copy.txt
[10] => New Text Document - Copy - Copy (2).txt
[11] => New Text Document - Copy - Copy (3).txt
[12] => New Text Document - Copy - Copy - Copy (2).txt
[13] => New Text Document - Copy - Copy - Copy - Copy.txt
[14] => New Text Document - Copy - Copy - Copy.txt
[15] => New Text Document - Copy - Copy.txt
[16] => New Text Document - Copy.txt
[17] => New Text Document.txt
)

And this is how Windows is sorting:

enter image description here

Upvotes: 1

Views: 212

Answers (2)

Tom Belote
Tom Belote

Reputation: 590

How about if you sort the array using natcasesort($fileNameList) like this:

<?php
$folder = opendir("folderx");
$fileNameList = array();

while(false !== ($fileName = readdir($folder))){
    array_push($fileNameList, $fileName);
}

function strip_non_cmp_characters($word) {
    return str_replace(array("(",")"," ","."),array("","","",""), $word);
}

function wincmp($a,$b) {
    return strnatcasecmp(strip_non_cmp_characters($a),
        strip_non_cmp_characters($b));
}

usort($fileNameList,"wincmp");

echo "<pre>";
print_r($fileNameList);
echo "</pre>";

Upvotes: 2

user925885
user925885

Reputation:

You can use scandir to order the files in alphabetical order. Opendir returns them as they are stored on the filesystem, not as they would show up in Windows.

Upvotes: 0

Related Questions