0

I'm creating an image gallery and would like for my most recent uploaded images to be at the front.

This is what I currently have:

$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    $supported_file = array('gif','jpg','jpeg','png');

    $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
    if (in_array($ext, $supported_file)) {
        echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
        echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
    } else {
        continue;
    }
}

But I'm not sure how to make it display in order of last uploaded.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • You will need an entirely different solution, probably based on a file iterator. My advice is to use the symfony finder component, which already has a number of sortations built in. See https://symfony.com/doc/current/components/finder.html – gview Jul 04 '17 at 22:31
  • There are 2 applicable sort methods already built in: sortByChangedTime() and sortByModifiedTime() – gview Jul 04 '17 at 22:35
  • use http://php.net/manual/en/function.filemtime.php to create an array of elements where key is filename and value is a reformatted timestamp, then `rsort()` Will that work for you? – mickmackusa Jul 04 '17 at 22:40
  • If Lambda7 doesn't post a fully refined answer, I will when I next get a chance. Your question is actually a two part question involving filtering the `glob()` results then sorting. There are previous answers on SO that state how to sort the files: https://stackoverflow.com/questions/2667065/sort-files-by-date-in-php and https://stackoverflow.com/questions/13572883/sort-array-of-files-by-last-modified . The glob() filtering is here: https://stackoverflow.com/questions/20929025/search-images-in-a-directory-using-glob-with-case-insensitivity – mickmackusa Jul 04 '17 at 23:27
  • and here: https://stackoverflow.com/questions/2520612/can-phps-glob-be-made-to-find-files-in-a-case-insensitive-manner – mickmackusa Jul 04 '17 at 23:27

1 Answers1

3
$files = glob("*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}",GLOB_BRACE);
$sorted_files=array(); /* a new array that have modification time as values
and files as keys the purpose is to sort files according to the values in reverse order */ 
foreach ($files as $file)
{
    $sorted_files[$file]=filemtime($file);
}
arsort($sorted_files);
foreach ($sorted_files as $image=>$mtime)
{           
    echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
    echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}
user10089632
  • 5,216
  • 1
  • 26
  • 34
  • yes, I did , no need to reformat the datetime expression as it will be compared as integer, yes I agree for values as keys, I'll edit this – user10089632 Jul 04 '17 at 22:44