0

I'm using this piece of php to pull the latest images from my directory, but I only want to display the latest 10 uploads instead of everything.

Anybody an idea how to alter the code so it does this? Thanks!

<?php
   $files = glob("images/*.*");
   for ($i=1; $i<count($files); $i++){

      $image = $files[$i];
      echo '<img src="'.$image .'" alt="Random image" id="lay"/>';
   }
?>
Anto
  • 4,265
  • 14
  • 63
  • 113
kreemers
  • 33
  • 11
  • how do know what the "latest" 10 are you dont check dates or sort by date or .. –  Feb 16 '15 at 19:51
  • 1
    How do you define "latest" ? Have you tried a sort and and for going from 1 to 10 ? – Niols Feb 16 '15 at 19:54

4 Answers4

1

There is also this using array_slice():

if($images = array_slice(glob("images/*.*")){
    //sort
    usort($images, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));
    //loop 10
    foreach (array_slice($images, 0, 10) as $image) {
       echo '<img src="'.$image.'" alt="..."/>';
    }
}
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

Take a look to piece of code used in a project. and you can adjust this according to your requirement.

$folder = 'images/';
$filetype = '*.*';
$files = glob($folder.$filetype);
$count = count($files);

$sortedArray = array();
for ($i = 0; $i < $count; $i++) {
    $sortedArray[date ('YmdHis', filemtime($files[$i]))] = $files[$i];
}

ksort($sortedArray);
echo '<table>';
foreach (array_slice($sortedArray), 0, 10) as &$filename) {
    #echo '<br>' . $filename;
    echo '<tr><td>';
    echo '<a name="'.$filename.'" href="#'.$filename.'"><img src="'.$filename.'" /></a>';
    echo substr($filename,strlen($folder),strpos($filename, '.')-strlen($folder));
    echo '</td></tr>';
}
echo '</table>';

and if you want to have the newest images at the top instead of at the bottom, then change this line:

ksort($sortedArray);

to this:

krsort($sortedArray);

Update apply the limit:

To apply the limit, you can simply apply counter or array slice function under final foreach and get top of your images.

Safoor Safdar
  • 5,516
  • 1
  • 28
  • 32
0

I like the foreach and array_slice but here in an alternate:

array_multisort(array_map('filemtime', $files=glob("images/*.*")), SORT_DESC, $files);

for($i=0; $i<10; $i++) {
    $image = $files[$i];
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0
//Get last 10
$limit = 10;
$arr = glob('/dir/dir/*.{jpg,jpeg,JPG,JPEG}', GLOB_NOESCAPE|GLOB_BRACE);
return array_slice($arr, (count($arr)-$limit), $limit);
Gigoland
  • 1,287
  • 13
  • 10