0

I was getting my photo from a folder randomly as the code below:

$imagesDir = 'tags/chilli_crab/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];

How can I change this to get the latest photo instead of the random one? Thanks!!!!!!

youaremysunshine
  • 331
  • 5
  • 16
  • 28

2 Answers2

2
array_multisort(array_map('filemtime', $images), SORT_NUMERIC, SORT_DESC, $images);

$latestimage = $images[0];
ina
  • 18,561
  • 37
  • 117
  • 197
Raab
  • 33,432
  • 4
  • 48
  • 63
0

Use below code:

$images = array();
foreach (scandir($folder) as $node) {
    $nodePath = $folder . DIRECTORY_SEPARATOR . $node;
    if (is_dir($nodePath)) continue;
    $images[$nodePath] = filemtime($nodePath);
}
arsort($images);
$newest = array_slice($images, 0, 5);

Hope this one help you

harsh4u
  • 2,450
  • 3
  • 22
  • 39