8

I was using count(glob("test/*")) to count the sub-folders in the test folder, but now that I also have files in the test folder, not just folders, I get incorrect results. Is there a way to modify the glob pattern so that it'll return only the folders, not files?

I've thought about a workaround. Get the total count of folders and files, get the count of files only, and then, subtract the count of files from the count of the whole.

$total_items  = count(glob("test/*"));
$total_files  = count(glob("test/*.*"));
$folder_count = $total_items - $total_files;

This works, but there might be a simpler way to do this.

akinuri
  • 10,690
  • 10
  • 65
  • 102

3 Answers3

18

You have to use the option GLOB_ONLYDIR to return only directories:

$total_items  = count( glob("test/*", GLOB_ONLYDIR) );
fusion3k
  • 11,568
  • 4
  • 25
  • 47
  • 1
    This is nice ☺ ☻. However, it doesn't count deeper in subfolders ... but this approach has helped me to do so by also combining it with this other [answer](http://stackoverflow.com/a/4339437/1883256). – Pathros Mar 08 '17 at 15:43
1

Your current solution may fail if there is a directory with a dot in its name like some.dir. For better results, you can check each of the results to see if they are files. Something like:

count(array_filter(glob("test/*"), "is_dir"))
kichik
  • 33,220
  • 7
  • 94
  • 114
0

I would try something like this, using readdir() and test with is_dir() (http://php.net/manual/en/function.opendir.php)

$dir = "test";
$n = 0;
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
    if ($file != "." && $file != ".." && is_dir($dir . DIRECTORY_SEPARATOR . $file)) {
        $n++;
    }
}
closedir($dh);
echo $n . " subdirectories in " . $dir;
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
hannenz
  • 503
  • 4
  • 14