PHP Get all subdirectories of a given directory

04/08/2020 03:00:02

How can I get all sub-directories of a given directory without files, .(current directory) or ..(parent directory) and then use each directory in a function?

Verified Answer (204 Votes)

03/26/2010 19:58:34

you can use glob() with GLOB_ONLYDIR option

or

$dirs = array_filter(glob('*'), 'is_dir');
print_r( $dirs);
204

Answer #2 (152 Votes)

06/09/2010 18:44:29

Here is how you can retrieve only directories with GLOB:

$directories = glob($somePath . '/*' , GLOB_ONLYDIR);
152

Answer #3 (43 Votes)

10/04/2013 15:14:38

The Spl DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.

$dir = new DirectoryIterator($path);
foreach ($dir as $fileinfo) {
    if ($fileinfo->isDir() && !$fileinfo->isDot()) {
        echo $fileinfo->getFilename().'<br>';
    }
}
43
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.