19

How can I reverse the sort by filename? Currently it displays all the text files in alphabetical / numerical order, but I'm trying to have it display in descending order instead. Right now, I have...

<?php  
foreach (glob("*.txt") as $filename) {
   include($filename);
}
?>

I'm pretty new to PHP, but I tried usort with array added on but that just resulted in it displaying only 1 of the text files, so either that doesn't work or I just coded it wrong.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
FrozenTime
  • 231
  • 1
  • 2
  • 9
  • 1
    The reverse sort function would be `rsort()` but needs to a be separate statement with a temporary array variable. – mario Oct 10 '11 at 04:00
  • I ran into some perceived alphabetic sorting problem but the underlying issue is that lowercased letters have higher ascii values than uppercased. A filename like myphoto1.jpg is returned after myPhoto2.jpg because of the capital P. – Dylan Valade Apr 01 '13 at 18:08

4 Answers4

38

You can use array_reverse:

foreach(array_reverse(glob("*.txt")) as $filename) { ...
Foo Bah
  • 25,660
  • 5
  • 55
  • 79
16

Just a addition to @Foo Bah's answer : When dealing with file names in a directory, I usually add natsort to prevent the typical ordering case :

  • 'image1.png'
  • 'image10.png'
  • 'image2.png'

natsort is a more user friendly sorting algorithm that will preserve natural numbering :

  • 'image1.png'
  • 'image2.png'
  • 'image10.png'

So FooBah's answer becomes :

$list = glob("*.jpg");
natsort($list);
foreach(array_reverse($list) as $filename) { ...

Please note that natsort is modifying the array passed in parameter and only returns a boolean.

Gabriel Glenn
  • 1,174
  • 1
  • 13
  • 30
4

For optimal performance, I would suggest to avoid unnecessary array processing (i.e. sorting or reversing) when dealing with large arrays.

Since the glob() function sorts the filenames in ascending order as default behaviour, you can simply loop through the resulting array in reverse order, and therefore avoid any other processing:

<?php
for($result = glob("*.txt"), $i = count($result); $i > 0; --$i) {
    include($result[$i-1]);
}

Cédric Françoys
  • 870
  • 1
  • 11
  • 22
2

The way to do it with usort() would be...

usort($files, function($a, $b) {
    return strcmp($b, $a);
});

CodePad.

alex
  • 479,566
  • 201
  • 878
  • 984