Reputation: 37
This is a script that shows images in a folder. But is there a way that I can show the latest image first? Instead of the other way around.
$images = glob('*.{gif,png,jpg,jpeg}', GLOB_BRACE); // formats to look for
$num_of_files = 2; // number of images to display
foreach($images as $image)
{
$num_of_files--;
if($num_of_files > -1) // this made me laugh when I wrote it
echo "<b>".$image."</b><br>Created on ".date('D, d M y H:i:s', filemtime($image)) ."<br><img src="."'".$image."' style='width: 95%'"."><br><br>" ; // display images
else
break;
}
Upvotes: 1
Views: 138
Reputation: 142
You need to put your images into an array and then sort by last modified.
Something like this:
$imagesToSort = glob('*.{gif,png,jpg,jpeg}');
usort($imagesToSort, function($a, $b) {
return filemtime($a) < filemtime($b);
});
Upvotes: 3
Reputation: 2763
glob()
doesn't care about which file came first or last. All it cares about are filenames. So you need to get all of the images and then you can try something like that to get them with reverse alphabetical order:
$images = glob('*.{gif,png,jpg,jpeg}', GLOB_BRACE);
$count = count($images) - 1;
$toShow = 2; // how many images you want to show
for ($i = 0; $i < $toShow; $i++, $count--) {
echo "<b>".$images[$count]."</b><br>Created on ".date('D, d M y H:i:s', filemtime($images[$count])) ."<br><img src="."'".$images[$count]."' style='width: 95%'"."><br><br>" ;
}
But if you want them in chronological order, you will need to foreach()
through all of them and sort them by filemtime
. This answer shows how to do it with usort()
's callback.
Upvotes: 0