Mike
Mike

Reputation: 5818

PHP only first level of subdirectories into an array

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();
        }
    }

Upvotes: 2

Views: 355

Answers (1)

Calimero
Calimero

Reputation: 4288

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

Upvotes: 4

Related Questions