Jump to content

Counting files in a directory


NotionCommotion

Recommended Posts

Looks like both http://php.net/manual/en/class.filesystemiterator.php and http://php.net/manual/en/globiterator.count.php (as well as other solutions) can be used.  Is one approach more suitable than the other?

$fi = new FilesystemIterator(__DIR__, FilesystemIterator::SKIP_DOTS);
printf("There were %d Files", iterator_count($fi));

$iterator = new GlobIterator('*.xml');
printf("Matched %d item(s)\r\n", $iterator->count());
Link to comment
Share on other sites

They are basically the same thing:

 

 

 

GlobIterator extends FilesystemIterator

 

FileSystemIterator, on it's own, will return all items in a directory (with the exception of being able to exclude the '.' and '..'). GlobIterator extends the function so you can have it only return specific items matching a pattern. Look at your own example. The GlobIterator will only count files (or directors) ending with '.xml'.

 

So, if you simple want to count all elements in a directory use FileSystemIterator. Else, if you are only looking for specific folders/files matching a pattern use GlobIterator.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.