What best practices should be followed when counting directories at a specific level in PHP?

When counting directories at a specific level in PHP, it is important to use a recursive function to traverse through the directories and count only the directories at the specified level. This can be achieved by keeping track of the current depth level and incrementing the count only when the desired level is reached.

function countDirectoriesAtLevel($dir, $level, $currentLevel = 0) {
    $count = 0;
    
    if ($currentLevel == $level && is_dir($dir)) {
        $count++;
    } elseif ($currentLevel < $level && is_dir($dir)) {
        $subDirs = scandir($dir);
        
        foreach ($subDirs as $subDir) {
            if ($subDir != '.' && $subDir != '..') {
                $count += countDirectoriesAtLevel($dir . '/' . $subDir, $level, $currentLevel + 1);
            }
        }
    }
    
    return $count;
}

$directory = '/path/to/directory';
$level = 2;

$count = countDirectoriesAtLevel($directory, $level);
echo "Number of directories at level $level: $count";