Search code examples
phparrayssortingecho

Sort array by time only on image echos


I'm trying to sort these echo results by using only time, and I can't seen to find a way to read when was the image placed on the folder (to sort them by the specific time).

<?php
  $all_files = glob(DIR_PATH."*.*");
  for ($i=0; $i<count($all_files); $i++)
    {
      $image_name = $all_files[$i];
      $supported_format = array('gif','jpg','jpeg','png');
      $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
      if (in_array($ext, $supported_format))
          {
            echo '<div class="col" ><img src="/led/images/autoplay/'.str_replace(DIR_PATH,'',$image_name) .' " /><div align="center"><br /><a href="javascript:deleteImg(\''.$image_name.'\')" class="myButton">Delete</a></div><br /></div>';

          } else {
              continue;
          }  
    }

?>

Solution

  • Maybe using usort() and filetime() function:

    $files = glob(DIR_PATH."*.*");
    usort( $files, function( $a, $b ) {
        return filemtime($a) - filemtime($b);
    } );
    
    foreach ($files as $file) {
        $image_name = $file;
        $supported_format = array('gif','jpg','jpeg','png');
        $ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
        if (in_array($ext, $supported_format))
        {
            echo '<div class="col" ><img src="/led/images/autoplay/'.str_replace(DIR_PATH,'',$image_name) .' " /><div align="center"><br /><a href="javascript:deleteImg(\''.$image_name.'\')" class="myButton">Delete</a></div><br /></div>';
    
        } else {
            continue;
        }
    }