Search code examples
phptreeviewscandir

how to list only all directories and subdirectories in a certain folder


For a treeview i use this function which gives me a complete summary of all the files and folders inside the main directory:

/* FUNCTION TREEVIEW directories & files */
function listFolderFiles($dir){
$files = preg_grep('/^([^.])/', scandir($dir));

// prevent empty ordered elements
if (count($files) < 1)
    return;

echo '<ul>';
foreach($files as $file){
    echo '<li class="treeview">'.$file;
    if(is_dir($dir.'/'.$file)) listFolderFiles($dir.'/'.$file);
    echo '</li>';
}
echo '</ul>';
}

This works fine! What do i have to change on the code that he only shows me the directories and not the files anymore?


Solution

  • Change

    foreach($files as $file){
        echo '<li class="treeview">'.$file;
        if(is_dir($dir.'/'.$file)) listFolderFiles($dir.'/'.$file);
        echo '</li>';
    }
    

    To

    foreach($files as $file){
        if(is_dir($dir.'/'.$file)) {
            echo '<li class="treeview">'.$file;
            listFolderFiles($dir.'/'.$file);
            echo '</li>';
        }
    }