Glob() sort by date order

I am using to restore a database and would like to display the latest first. At the moment, it is display ad-hoc with no sort on it. I would be grateful if someone could help with this.

Many thanks

<!--  START OF RESTORE FUNCTION  -->
    <div id="restore">
      <div id="restoreTxt">
        This area is for restoring created database backups. To restore a backup, simply<br />select the backup you require and click the 'Restore Backup' button.
      </div>
      <select class="testdept chosen-select" id="restoredept" data-placeholder="Select a database to restore">
        <option value=""></option>
        <?php
          $files = "sqlbackup2/*";
          foreach(glob($files) as $file) {
          if(!is_dir($file)) {
          $output = date("m/d/Y H:i",filemtime($file));
          $filebackup = $file;
          echo "<option value=".basename($filebackup).">".$output."</option>";
            }
        }
      ?>
      </select>
      <div class="restoretxt"></div>
      <input type="button" id="restoreBtn" value="Restore Backup" disabled />
      <div class="rssuccesstxt"></div>
      <div class="rserrortxt"></div>
      <div class="rsajaxtxt"></div>
    </div>
  </div>

just give your array of file-path to usort() with a custom function that uses filetime() on each path and returns if its greater or not.

Chorn
Sorry not following the logic of your answer. Could you show with example please. Many thanks

Using your example as a starting point:

$files = [];
foreach (glob('sqlbackup2/*') as $file) {
    if (!is_dir($file)) {
        $files[] = $file;
    }
}

$sortedFiles = usort(
    $files,
    function($file1, $file2) {
        return filemtime($file1) <=> filemtime($file2);
    }
);

foreach ($sortedFiles as $file) {
    printf(
        '<option value="%s">%s</option>',
        basename($file),
        date('m/d/Y H:i', filemtime($file))
    )
}

I like that better than what I was thinking of. It would be possible to create a new array using file ↔ mtime as keys ↔ values and use sort ↔ ksort. But that could leave open a possible bug in the (even if remote) event that any files had the same values as other files.

My code suffers from the same problem.

From the manual on usort:

If two members compare as equal, their relative order in the sorted array is undefined.

What I do like about coding like this instead of key => value is that this is quite easy to follow, whereas juggling and sorting with key => value it’s a lot easier to get lost in the details.

1 Like

Thank you very much

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.