The problem is simple. array_reverse()
does not modify by reference. You are confusing the behavior of sort()
ing functions. Instead, you merely need to use the returned value that it generates. That said, there is a better way. Read on...
Since PHP5.4, rsort($array, SORT_NATURAL)
will sort your array in DESC order and treat consecutive numbers as numbers instead of strings. This is a more direct and concise way technique versus natsort()
ing then array_reverse()
ing.
(Demo)
(Demo with .jpg
extensions)
(Demo with static string before numbers)
I recommend using glob()
to scan your directory. This way you can add the .png
filter in the same call.
$dir = 'dead_dir/dead_content/';
$filepaths = glob($dir . '*.png');
rsort($filepaths, SORT_NATURAL);
foreach ($filepaths as $filepath) {
echo '<img src="' . $filepath . '" />';
}
If you would rather omit the path and just return the filenames, just change your current working directory.
chdir('dead_dir/dead_content');
$filenames = glob('*.png');
rsort($filenames, SORT_NATURAL);
foreach ($filenames as $filename) {
echo "<div>.png filename => $filename</div>";
}
Now, if you require more specialized handling of the filenames, then a custom sorting function may serve you well.
As demonstrated in the following snippet, the spaceship operator will auto-magically type juggle digital strings as integers and give the same result as the rsort()
solution above. Using the spaceship operator is still more direct than using natsort()
then array_reverse()
.
Code: (Demo)
$filenames = ["10", "1", "100", "1000", "20", "200", "2"];
usort($filenames, function($a, $b) {
return $b <=> $a;
});
var_export($filenames);
Output:
array (
0 => '1000',
1 => '200',
2 => '100',
3 => '20',
4 => '10',
5 => '2',
6 => '1',
)
If your filenames have leading or trailing non-numeric characters, you can perform the necessary manipulations to strip the unwanted characters while comparing inside of usort()
.
If anyone is not familiar with how custom sorting works with the spaceship operator...
- To achieve ASC order, write
$a <=> $b
.
- To achieve DESC order, write
$b <=> $a
.
array_reverse
. – Lafferty