获取子文件夹的数量

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.

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

$total_items  = count( glob("test/*", GLOB_ONLYDIR) );

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;

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"))