Reputation: 43
I am new to PHP and basically I am trying to display an image gallery that retrieves photos from a folder. The thing is, I want the image with the most recent upload date to appear at the very beginning, and so on until the oldest one in the bottom.
This is what my PHP looks like (the important bit I guess)
$files = scandir('uploads/thumbs');
$ignore = array( 'cgi-bin', '.', '..');
foreach ($files as $file) {
if(!in_array($file, $ignore)) {
echo '<img src="uploads/thumbs/' . $file . '" />';
}
}
I would like to know if there's a way by PHP or maybe with a little help of CSS to display them in reverse order, making the newest one always to appear at the top of the page.
Any help or suggestion is very appreciated, regards from Argentina!
Upvotes: 0
Views: 3195
Reputation: 1
If you have your images in a database you can just do
$sql1 = "SELECT * FROM images ORDER BY img_id DESC";
Upvotes: 0
Reputation: 197680
Next to your $files
you can obtain the modification time of each file and then sort the $files
array based on the time values acquired. A function which sorts two or more arrays with the value of an array is array_multisort
:
$files = scandir($path);
$ignore = array( 'cgi-bin', '.', '..');
# removing ignored files
$files = array_filter($files, function($file) use ($ignore) {return !in_array($file, $ignore);});
# getting the modification time for each file
$times = array_map(function($file) use ($path) {return filemtime("$path/$file");}, $files);
# sort the times array while sorting the files array as well
array_multisort($times, SORT_DESC, SORT_NUMERIC, $files);
foreach ($files as $file) {
echo '<img src="uploads/thumbs/' . $file . '" />';
}
Upvotes: 1