Search code examples
phpdirectoryglobdirectory-structure

Array with directories and subdirectories PHP slow


I created this function:

function expandDirectories2($base_dir) {
      $directories = array();
      $folders = glob($base_dir."*", GLOB_ONLYDIR);
      foreach($folders as $file) {
            if($file == '.' || $file == '..') continue;
            $dir = $file;
            if(is_dir($dir)) {
                $directories []= $dir;
                $directories = array_merge($directories, expandDirectories2($dir));
            }
      }
      return $directories;
}

print_r(expandDirectories2("./"));

This function read all directories and subdirectories of a specified folder. The problem is it takes so much to load the page and sometimes it shows memory_exhausted error.

I only want to make an array with directories and subdirectories of a folder. I don't want to be hierarchical and the ordering isn't important.

Example: This is the folder structure:

   - PARENT FOLDER:
     - 2014
        - 01
        - 02
        - 03
        - 04
        - 05
        - 06
        - 07
        - 08
        - 09
        - 10
        - 11
        - 12
     - 2015
        - 01
        - 02
        - 03
        - 04
        - 05
        - 06
        - 07
        - 08
        - 09
        - 10
        - 11
        - 12

Then the array should be:

./2014
./2014/01
./2014/02
./2014/03
./2014/04
./2014/05
./2014/06
./2014/07
./2014/08
./2014/09
./2014/10
./2014/11
./2014/12
./2015
./2015/01
./2015/02
./2015/03
./2015/04
./2015/05
./2015/06
./2015/07
./2015/08
./2015/09
./2015/10
./2015/11
./2015/12

The ordering is not important. The array will not contain files. Only dirs.

How can I do this faster?

Thank you all!!!


Solution

  • Try using DirectoryIterator. It should be much faster.

    function expandDirectories2($path) {
        $directories = array();
        $dir = new DirectoryIterator($path);
        foreach ($dir as $fileinfo) {
            if ($fileinfo->isDir() && !$fileinfo->isDot()) {
                $directories[]= $fileinfo->getPathname();
                $directories = array_merge($directories, expandDirectories2($fileinfo->getPathname()));
            }
        }
        return $directories;
    }
    

    Check more info here: http://php.net/manual/en/class.directoryiterator.php