Sorting files with files () and usort () gives random results

I use usort(), and filemtime()to sort by date modified files, but it randomly returns the files in the wrong order. I probably miss something very simple, but I can’t understand that.

usort($user_files, function($a, $b) {
    return filemtime($a) > filemtime($b);
});
foreach ($user_files as $f) {
    echo $f . "<br />";
}

After that I upload the file. Full code .

When uploading files 1.txt... 10.txtto check what happens to the displayed results, were:

6.txt
5.txt
4.txt
3.txt
2.txt
1.txt
7.txt Uploaded!

As expected. Then when I reached 8.txt:

6.txt
7.txt
5.txt
4.txt
2.txt
3.txt
1.txt
8.txt Uploaded!

Another time it was ok until I reached 10.txt:

7.txt
8.txt
9.txt
6.txt
5.txt
2.txt
3.txt
4.txt
1.txt
10.txt Uploaded!

While returning ls -t:

10.txt  9.txt  8.txt  7.txt  6.txt  5.txt  4.txt  3.txt  2.txt  1.txt

So ... what is going on there?

Debian Wheezy 7.4, up-to-date.
PHP Version 5.4.4-14+deb7u8
Linux pc 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 x86_64
FPM/FastCGI
nginx/1.2.1
+4
2

, , , , usort. , , , . , filemtime . , php .

0

usort http://www.php.net/manual/en/function.usort.php

value_compare_func

, , , , , .

">":

{
    return filemtime($a) > filemtime($b);
}

(http://www.php.net/manual/en/language.operators.comparison.php), ", " aka > true false, // , .

$a > $b , , $a $b.

"" "-" filemtime s, Man , filemtime (http://www.php.net/manual/en/function.filemtime.php).

- (googled filemtime usort - ): , ?, , :

  if (filemtime($a) === filemtime($b)) return 0;
  return filemtime($a) < filemtime($b) ? -1 : 1; 
+3

Source: https://habr.com/ru/post/1536030/


All Articles