Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return total number of files within a folder using PHP

Is there a better/simpler way to find the number of images in a directory and output them to a variable?

function dirCount($dir) {
  $x = 0;
  while (($file = readdir($dir)) !== false) {
    if (isImage($file)) {$x = $x + 1}
  }
  return $x;
}

This seems like such a long way of doing this, is there no simpler way?

Note: The isImage() function returns true if the file is an image.

like image 985
PHLAK Avatar asked Oct 22 '08 03:10

PHLAK


1 Answers

Check out the Standard PHP Library (aka SPL) for DirectoryIterator:

$dir = new DirectoryIterator('/path/to/dir');
foreach($dir as $file ){
  $x += (isImage($file)) ? 1 : 0;
}

(FYI there is an undocumented function called iterator_count() but probably best not to rely on it for now I would imagine. And you'd need to filter out unseen stuff like . and .. anyway.)

like image 173
bbxbby Avatar answered Oct 13 '22 07:10

bbxbby