How to get list of subdirectories in PHP

Definition

This page explains how to get the full list of sub directories from a given (root) diretory in PHP

PHP source code

The following function returns the full list of subdirectories of $dir:

    // Return an array with the list of sub directories of $dir
    function getSubDirectories($dir)
    {
        $subDir = array();
        // Get and add directories of $dir
        $directories = array_filter(glob($dir), 'is_dir');
        $subDir = array_merge($subDir, $directories);
        // Foreach directory, recursively get and add sub directories
        foreach ($directories as $directory) $subDir = array_merge($subDir, getSubDirectories($directory.'/*'));
        // Return list of sub directories
        return $subDir;
    }

Minimal version:

    function getSubDirectories($dir)
    {
        $subDir = array();
        $directories = array_filter(glob($dir), 'is_dir');
        $subDir = array_merge($subDir, $directories);
        foreach ($directories as $directory) $subDir = array_merge($subDir, getSubDirectories($directory.'/*'));
        return $subDir;
    }

See also


Last update : 09/21/2018