-1

I found on YT a php code to display images from directory. Everything works perfect, but I need to display the latest photos on the top. Can anyone help me?

<?php
    $dir = 'foto';
    $file_display = array('jpg', 'jpeg');

    if (file_exists($dir) == false) {
        echo 'Gallery \'', $dir, '\' not found!';
    } else {
        $dir_contents = scandir($dir);

        foreach ($dir_contents as $file) {
            $file_type = strtolower (end(explode('.', $file)));

            if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
                echo '<div id="', $file,  '"><img src="', $dir, '/', $file, '" alt="', $file, '" /></div>';
            }
        }
    }
?>
initramfs
  • 8,275
  • 2
  • 36
  • 58
pobliska
  • 237
  • 1
  • 4
  • 13
  • I think you need to look into the PHP filemtime function, in order to pull out the modified date of a file - I don't think that's possible with scandir alone. Then look here http://php.net/manual/en/array.sorting.php for information regarding sorting arrays, and piecing those together you should be able to do it. – Darren Crabb Oct 14 '13 at 16:19
  • Possible duplicate of http://stackoverflow.com/questions/11923235/scandir-to-sort-by-date-modified – dave Oct 14 '13 at 16:21

2 Answers2

2

Less code:

array_multisort((
    array_map(
        'filemtime', ($files = glob(
            "$dir/*.{jpg,jpeg}", GLOB_BRACE)))), SORT_DESC, $files);
  • Glob for the specific files and store in $files
  • Get the file modification time for each and sort $files on the times

foreach on $files and display.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

I think you will need to sort images by date. Someone has written another variant of scandir() function here: https://stackoverflow.com/a/11923516/1644017

You can get that function and change $dir_contents = scandir($dir); to: $dir_contents = scan_dir($dir); in your code.

Community
  • 1
  • 1
Azamat
  • 435
  • 5
  • 13