0

I am new to php so please be gentle. I am trying to sort the images I have in a gallery from newest to oldest. I have look online but its quite confusing. Any help would be appreciated.

<?php
  $files = glob("Pictures/*.*");
for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    print $image ."<br />";
    echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}

    

            // open this directory
            $myDirectory = opendir("Pictures/");

            // get each entry
            while($entryName = readdir($myDirectory)) {
            $dirArray[] = $entryName;
            }

            // close directory
            closedir($myDirectory);

            //  count elements in array
            $indexCount = count($dirArray);


?>
  • Does this answer your question? [glob() - sort array of files by last modified datetime stamp](https://stackoverflow.com/questions/124958/glob-sort-array-of-files-by-last-modified-datetime-stamp) – Justinas Nov 17 '21 at 13:43
  • Go through your array of files and for each file get the file modified time using `filemtime` function. Then sort your array using the filemtime column. – slashroot Nov 17 '21 at 13:43

1 Answers1

0

We first retrieve all the files like you already did.

$files = glob('pictures/*.*');

Than we sort these files by mtime.

usort($files, function($a, $b) {
    return filemtime($b) - filemtime($a);
});
Yaro
  • 43
  • 4
  • Hi guys, so I added the below code and it made not difference at all. usort($files, function($a, $b) { return filemtime($b) - filemtime($a); }); – Craig E Nov 17 '21 at 22:16
  • You need to add it after the definition of files. If you did so and did not achieve the desired result than please explain the problem and give us the output. – Yaro Nov 18 '21 at 14:17