0

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!

fs2338
  • 43
  • 1
  • 5
  • 1
    I think you're looking for something like http://stackoverflow.com/questions/5361614/sorting-scandir-by-date-descending-order – tjm Jul 02 '11 at 15:55

2 Answers2

1

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 . '" />';
}
hakre
  • 193,403
  • 52
  • 435
  • 836
  • Thanks hakre and tjm for both of your answers, they're really helpful, but actually I'm having a hard time getting it to work. I'm not really sure about PHP, I'm just cutting and pasting here and there. I've posted here the whole thing, maybe you could help me out to getting it done: Thanks! http://jsfiddle.net/salvetti/FzAXg/ – fs2338 Jul 02 '11 at 18:39
  • @Francisco Salvetti: Sorry, but jsfiddle does not work with my browser. Please paste into some webservice that does work w/o javascript. – hakre Jul 03 '11 at 10:04
  • Oh sure, sorry about that. Here's the link: http://shorttext.com/es3tj3ih1nz - Thanks for taking the time, I really appreciate it :) – fs2338 Jul 03 '11 at 20:52
0

If you have your images in a database you can just do

$sql1 = "SELECT * FROM images ORDER BY img_id DESC";