1

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;
   }
Lernkurve
  • 20,203
  • 28
  • 86
  • 118
Dylan_R
  • 37
  • 7

2 Answers2

3

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);
});
  • Can u tell me how I put this to use?? – Dylan_R Mar 02 '15 at 10:44
  • @Dylan_R it gives you array of every image. array is sorted by `filemtime()` ascending. It means that the oldest files (the ones with lower `filemtime`) are first. – Forien Mar 02 '15 at 11:08
0

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.

Community
  • 1
  • 1
Forien
  • 2,712
  • 2
  • 13
  • 30