Count All Directories in Given Directory and Subdirectories using PHP

RecursiveDirectoryIterator class

<?php

$rootDir = 'test_dir';

$it = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootDir, RecursiveDirectoryIterator::SKIP_DOTS),
    RecursiveIteratorIterator::SELF_FIRST
);

$numberOfDirs = 0;

foreach ($it as $fileInfo) {
    if ($fileInfo->isDir()) {
        $numberOfDirs++;
    }
}

echo $numberOfDirs;

Leave a Comment

Cancel reply

Your email address will not be published.