1

I have PHP file that generates gallery from a directory of images.

I want to sort images by modification date.

I'm trying to use filemtime function then sort function using the following code:

<?php
  $src_folder = 'gallery';  
  $src_files = scandir($src_folder); 

  function filetime_callback($a, $b) {
    if (filemtime($src_folder.'/'.$a) === filemtime($src_folder.'/'.$b)) return 0;
    return filemtime($src_folder.'/'.$a) > filemtime($src_folder.'/'.$b) ? -1 : 1; 
  }

  $files = array();
  usort($files, "filetime_callback");
              
  foreach($src_files as $file) {
   echo $file . ' - ' . date ("F d Y H:i:s.", filemtime($src_folder.'/'.$file)) . '<br>';
  }
?>

And the output is like this:

image01.jpg - October 22 2017 19:40:02.
image02.jpg - October 22 2017 19:39:19.
image03.jpg - October 22 2017 19:39:23.
image04.jpg - October 22 2017 19:39:28.

It is not sorted by modification date.

How can I make my code work?

Dharman
  • 30,962
  • 25
  • 85
  • 135
ramchi
  • 13
  • 3

2 Answers2

2
function scan_dir($dir) {
      $ignored = array('.', '..', '.svn', '.htaccess');
      $files = array();
      foreach (scandir($dir) as $file) {
          if (in_array($file, $ignored))  {
              continue;
          }
          $filemtime = filemtime($dir . '/' . $file);
          $files[$file] = $filemtime;
      }

      arsort($files);
      $files = array_keys($files);

      return ($files) ? $files : false;
  }

  $src_folder = 'gallery';

  $files = scan_dir($src_folder);
  
  foreach($files as $file) {
      echo $file . ' - ' . date ("F d Y H:i:s.", filemtime($src_folder.'/'.$file)) . '<br>';
  }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Sayonara
  • 267
  • 1
  • 10
  • 1
    It's just a similar concept, just taking the modification date as timestamp, putting into array and sorting it via arsort(), in order to get the desired result. The guy said that he is not a php dev, he needs just a solution and I hope this will help him, I don't think he is here to learn PHP from the bottom ... – Sayonara Oct 22 '17 at 19:02
0

Variable scope is your issue, $src_folder is undefined in the context of your filetime_callback function.

Do not disable error reporting on development environments.


Another problem is you aren't sorting the correct array. You're creating an empty array $files then trying to sort that instead of the $src_files array.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95