count number of .jpg's in a directory, sort in array to create links

I need to count number of images (.jpg) in a folder, sort them by name so I can dynamically create next and previous buttons in a gallery carousel.
Who is Participating?
sbickerstaffConnect With a Mentor Commented:
Here's some code I developed last year or the year before, based on the Zeneth Picure Gallery source code.  I've changed my code to return a count for you rather than what i was doing with it.  I haven't tested this version but the original checked and returned a list of all the jpgs or pngs

$pics = directory("../pic_directory/", "jpg,JPG,JPEG,jpeg,png,PNG");

function directory($dir, $ext) {
  $extlist = explode(",", $ext);
  $piccount = 0;
  // Open a known directory, and proceed to read its contents
  if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
      while (($file = readdir($dh)) !== false) {
        $pos = strrpos($file, '.');
        if(!$pos) {
          $ext = 'Unknown Filetype';
        $str = substr($file, $pos, strlen($file));
        $ext = $str;
        if (($file != "." && $file != "..") && (filetype($dir . $file) == "file") && (in_array($ext,$extlist) !== false)) {
  return $piccount;

Open in new window

A nudge in the right direction would be opendir():

You can traverse the folder to get the document names and types, separate only the jpg files into an array then do whatever else you want to do.
just noticed, that should be

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.