2

I'm trying to get only the first level of subdirectories into an array. Does someone know a slimmer and faster way to do this?

    $dirs =  new RecursiveDirectoryIterator('myroot', RecursiveDirectoryIterator::SKIP_DOTS);
    $files = new RecursiveIteratorIterator($dirs, RecursiveIteratorIterator::SELF_FIRST);

    $dir_array = array();
    foreach( $files AS $file) 
    {           
        if($files->isDot()) continue;
        if($files->getDepth() > 0) continue;

        if( $files->isDir() )
        {
            $dir_array[] = $file->getFilename();
        }
    }

1 Answer 1

4

Simple as this:

$array = glob('myroot/*', GLOB_ONLYDIR);

To get only the base directory name and not the full path:

$array = array_map('basename', glob('myroot/*', GLOB_ONLYDIR));

See http://php.net/glob

Sign up to request clarification or add additional context in comments.

3 Comments

yes, absolutely. There are iterators for recursively iterating as you already know.
ok, but that gives me the full paths rather than an array with only the subdir names like above.
@Mike: Map the array with basename

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.