0

I have a program that grab all image from directory and here the code:

$dir = dir("tags/carrot_cake");
while($filename=$dir->read()) {

    if($filename == "." || $filename == ".." ||  $filename == $first_image) continue;

     echo "<img src='tags/carrot_cake/".$filename."'class='img_235x235' />

How can I check the image date and grab the latest image first? Thanks!

youaremysunshine
  • 341
  • 6
  • 16
  • 28

1 Answers1

2

You can use the filemtime() function to find the modification date of each file. This can be used as a key to sort the array using uksort() before it is processed in the loop.

This will put the array in ascending order of file modification time, i.e. those with the earliest mtime first. You can then either reverse the array, or iterate through it backwards.

<?php
    function mtimecmp($a, $b) {
        $mt_a = filemtime($a);
        $mt_b = filemtime($b);

        return ($mt_a == $mt_b) ? 0 : (($mt_a < $mt_b) ? -1 : 1);
    }

    $dirname = "tags/carrot_cake";
    $images = glob($dirname."*.jpg");
    usort($images, "mtimecmp");
    array_reverse($images);

    foreach ($images as $image) {
        echo '<img src="tags/carrot_cake/'.$image.'" class="img_235x235"/><br />';
    }
?>
Joran Den Houting
  • 3,149
  • 3
  • 21
  • 51