How can PHP scripts be optimized to accurately count subdirectories within a specified directory?

To accurately count subdirectories within a specified directory in PHP, you can use the `scandir()` function to get a list of all files and directories within the specified directory, then loop through this list and check if each item is a directory using `is_dir()`. Increment a counter for each directory found to get the total count of subdirectories.

$directory = 'path/to/directory';
$subdirectoryCount = 0;

$files = scandir($directory);

foreach ($files as $file) {
    if ($file != '.' && $file != '..' && is_dir($directory . '/' . $file)) {
        $subdirectoryCount++;
    }
}

echo "Total subdirectories in $directory: $subdirectoryCount";