Get all subdirectories of a given directory in PHP
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.
|
1 2 3 4 5 6 |
<?php $path = '/path/to/directory'; $directories = array_filter(glob($path.'/*'), 'is_dir'); print_r($directories); ?> |
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.
|
1 2 3 4 5 6 |
<?php $path = '/path/to/directory'; $directories = glob($path.'/*', GLOB_ONLYDIR); print_r($directories); ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $path = '/path/to/directory'; $iterator = new DirectoryIterator($path); foreach ($iterator as $fileinfo) { if ($fileinfo->isDir() && !$fileinfo->isDot()) { echo $fileinfo->getFilename(), PHP_EOL; } } ?> |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php $path = '/path/to/directory'; $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); foreach ($iterator as $file) { if ($file->isDir()) { echo $file->getRealpath(), PHP_EOL; } } ?> |
That’s all there is to getting all the subdirectories of a given directory in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)