List the folders of a route (get subdirectories)

4

What I'm looking for is to make an array that contains only the names of folders (directories) of a given route.

I tried scandir ():

$scan = scandir(realpath(__dir__));
for ($i = 0; $i < count($scan); $i++) {
    if (is_file(dirname(__file__) . '\' . $scan[$i])) {
    //Si es un archivo Eliminalo en su posicion $i
        array_splice($scan, $i, 1);
    }
}

But there is still an .sql file in the array that should not be there:

[0] => . [1] => .. [3] => controladores [7] => modelos [8] => vistas [9] => zonaedu.sql
                                                //en el último elemento --> ^^^^^^^^^^^

Why is this?

    
asked by Angel Zambrano 12.02.2018 в 23:44
source

1 answer

6

The problem is that you are using a \ instead of / , or even better DIRECTORY_SEPARATOR . And both is_dir () and is_file () need the full path.


List all subdirectories in a folder (not recursive)

  • An alternative, if you are also interested in removing the symbolic links, is using is_dir () :

    $carpetaBase = realpath(__dir__);
    $resultado = array();
    
    foreach(scandir($carpetaBase) as $carpeta) {
        if ($carpeta != '.' && $carpeta != '..' && is_dir($carpetaBase . DIRECTORY_SEPARATOR . $carpeta)) {
            $resultado[] = $carpeta;
        }
    }
    
    print_r($resultado);
    

  • Or we can use glob () with the option GLOB_ONLYDIR :

    $carpetaBase = getcwd();
    $resultado = array();
    
    foreach(glob($carpetaBase . '/*', GLOB_ONLYDIR) as $carpeta) {
        $resultado[] = basename($carpeta);
    }
    
    print_r($resultado);
    

  • Or with the class DirectoryIterator :

    $resultado = array();
    $di = new DirectoryIterator($carpetaBase);
    foreach ($di as $carpeta) {
        if ($carpeta->isDir() && !$carpeta->isDot()) {
            $resultado[] = $carpeta->getFilename();
        }
    }
    
  • answered by 13.02.2018 / 00:24
    source