Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

glob() — Sort by Name [duplicate]

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.

like image 583
FrozenTime Avatar asked Oct 10 '11 03:10

FrozenTime


People also ask

What is glob glob () in Python?

Python glob. glob() method returns a list of files or folders that matches the path specified in the pathname argument. This function takes two arguments, namely pathname, and recursive flag. pathname : Absolute (with full path and the file name) or relative (with UNIX shell-style wildcards).

What does glob glob return?

The glob. glob returns the list of files with their full path (unlike os. listdir()) and is more powerful than os. listdir that does not use wildcards.


3 Answers

You can use array_reverse:

foreach(array_reverse(glob("*.txt")) as $filename) { ...
like image 162
Foo Bah Avatar answered Oct 21 '22 05:10

Foo Bah


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.

like image 37
Gabriel Glenn Avatar answered Oct 21 '22 06:10

Gabriel Glenn


For optimal performance, I would suggest to avoid unnecessary array processing (i.e. sorting or reversing) when dealing with potentially 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]);
}

like image 29
Cédric Françoys Avatar answered Oct 21 '22 04:10

Cédric Françoys