Return to Snippet

Revision: 38141
at December 26, 2010 16:50 by noelj


Initial Code
<?php
function dir_recursive($path, $parent = ''){
    $files = array();
    
    $d = dir($path);
    while (false !== ($entry = $d->read())) {
        if($entry == '.' || $entry == '..')
            continue;
        
        //if this is a directory, loop inside its contents
        if(is_dir($d->path.'/'.$entry)){
            //if parent dir given, then create another array dimension to be used to store files under this parent
            if(!empty($parent)){
                $files[$parent][$entry] = dir_recursive($d->path.'/'.$entry, $entry);
            }else
                $files[$entry] = dir_recursive($d->path.'/'.$entry, $entry);
        }else
            $files[$entry] = $entry;
        
        //reset parent dir given, so it won't create another array dimension for the next loop of subdirectory
        $parent = '';
    }
    $d->close();
    
    return $files;
}

//usage
$files = dir_recursive('.');
echo '<pre>'; print_r($files);

?>

Initial URL

                                

Initial Description

                                

Initial Title
Scan directory contents recursively

Initial Tags
files

Initial Language
PHP