0

I'm using the following PHP script to show me the images contained in a directory..

$imagetypes = ['image/jpeg', 'image/gif', 'image/png'];
  function getImages($dir)
  {
    // array to hold return value
    $retval = [];

    // add trailing slash if missing
    if(substr($dir, -1) != "/") {
      $dir .= "/";
    }

    // full server path to directory
    $fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";

    $d = @dir($fulldir) or die("getImages: Failed opening directory {$dir} for reading");
    while(FALSE !== ($entry = $d->read())) {
      // skip hidden files
      if($entry{0} == ".") continue;

      // check for image files
      $f = escapeshellarg("{$fulldir}{$entry}");
      $mimetype = trim(shell_exec("file -bi {$f}"));
      foreach($GLOBALS['imagetypes'] as $valid_type) {
        if(preg_match("@^{$valid_type}@", $mimetype)) {
          $retval[] = [
           'file' => "/{$dir}{$entry}",
           'size' => getimagesize("{$fulldir}{$entry}")
          ];
          break;
        }
      }
    }
    $d->close();

    return $retval;
  }

  // fetch image details
  $images = getImages("imguploader/UploadFolder");

  // display on page
  foreach($images as $img) {
    echo "<img class=\"photo\" src=\"{$img['file']}\" {$img['size'][3]} alt=\"\">\n";
  }

This is all working very nicely and the only thing I'd now like to do is to have them display in filename alphabetical order instead of the seemingly random order they appear in currently.

Glen Keybit
  • 296
  • 2
  • 15

1 Answers1

1

Try a usort, If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:

function sortByOrder($a, $b) {
    return $a['file'] - $b['file'];
}

usort($images, 'sortByOrder');

Starting in PHP 5.3, you can use an anonymous function:

usort($images, function($a, $b) {
    return $a['file'] - $b['file'];
});

And finally with PHP 7 you can use the spaceship operator:

usort($images, function($a, $b) {
    return $a['file'] <=> $b['file'];
});
Mike Foxtech
  • 1,633
  • 1
  • 6
  • 7
  • Hi, thank you for taking the time to reply, for further info I'm using PHP 7 but sadly I am too novice to know how to implement the example you have given into my actual code! – Glen Keybit Jan 11 '20 at 14:42
  • asort on the $image array did the trick for me when I tried usort the order remained the same. thanks again for your time. – Glen Keybit Jan 11 '20 at 16:03