Christopher Ward
Christopher Ward

Reputation: 69

How to get image files from a directory and order by last modified?

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.

Upvotes: 0

Views: 1720

Answers (1)

user10089632
user10089632

Reputation: 5550

$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 />";
}

Upvotes: 3

Related Questions