Search code examples
phpiterationdir

php - Get List Of First Children Directory Names


How to get a list of first children directory names inside a directory?

Here is an example tree:

dir /
    dir_first a /
                  dir second aa
                  dir second ab
                  dir second ac                 
    dir_first b /
                  dir second ba
                  dir second bb
                  dir second bc 
    dir first c /
                  dir second ca
                  dir second cb
                  dir second cc 

I found the way of iterating through the dir here, but this is listing all the second level childrens too and also their full paths, while I want only the directory's name like dir_first a etc.:

$iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($dir_path), 
            RecursiveIteratorIterator::SELF_FIRST);

foreach($iterator as $file) {
    if($file->isDir()) {
        echo $file->getRealpath();
    }
}

Solution

  • glob allows you to enter a path and then use a flag to return only directories.

    $files = glob('mydir/*',GLOB_ONLYDIR);
    var_dump($files);