Search code examples
phpsortingfilenamesreversenatsort

Sorting an array of directory filenames in descending natural order


I have a content directory to be returned in descending natural order.

I'm using scandir() and natsort(), but the addition of array_reverse() yields no results.

I've been researching using a combination of opendir() and readdir() as well what ever else to affect this outcome.

The items to be sorted are numbered image files. They are to be returned as: 10 9 8 7 and so on, but like from like 1000 999 998 997 ... until 0

Here's my current code:

$dir = 'dead_dir/dead_content/';
$launcher = scandir($dir);
natsort($launcher);
array_reverse($launcher, false);
foreach ($launcher as $value) {
    if (in_array(pathinfo($value, PATHINFO_EXTENSION), array('png'))) {
        echo '<img src="dead_dir/dead_content/'.$value.'" />'
    }
}

Solution

  •  $dir='dead_dir/dead_content/';
     $launcher= scandir($dir);
     natsort($launcher);
     $r_launcher = array_reverse($launcher,true);
    
     foreach($r_launcher as $value ){
       if(in_array(pathinfo($value, PATHINFO_EXTENSION),array('png'))){
           echo '<img src="dead_dir/dead_content/'.$value.'" />'}}