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.
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).
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.
You can use array_reverse
:
foreach(array_reverse(glob("*.txt")) as $filename) { ...
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.
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]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With