This article demonstrates how to get all subdirectories of a given directory in PHP.

1. Using glob() function

You can easily list all files in a directory using glob() function. The glob() function takes a pattern and returns an array containing the pathnames matching that pattern. You can then filter out all subdirectories in the returned files using the array_filter() function with is_dir() as the callback. The is_dir() function returns true if the file is a directory, and false otherwise.

Download Code

 
The above implementation is a little verbose. A better option is to retrieve only directories with the glob() function. This can be done using the GLOB_ONLYDIR flag, which returns only directory entries matching the pattern.

Download Code

2. Using DirectoryIterator class

The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories. Following is a simple example demonstrating the usage of the DirectoryIterator class. The solution iterates over the contents of the directory using a directory iterator and then filters out all directories with the DirectoryIterator::isDir() function.

Download Code

3. Using RecursiveDirectoryIterator class

Another option is to use the RecursiveDirectoryIterator class to recursively iterate over the filesystem directories. For example, the following solution will list the subdirectories of a directory using RecursiveIteratorIterator in combination with RecursiveDirectoryIterator. It uses the DirectoryIterator::isDir() function to determine if the current item is a directory.

Download Code

That’s all there is to getting all the subdirectories of a given directory in PHP.