Skip to content

Instantly share code, notes, and snippets.

@jasonhofer
Last active July 15, 2022 10:26
Show Gist options
  • Save jasonhofer/2368606 to your computer and use it in GitHub Desktop.
Save jasonhofer/2368606 to your computer and use it in GitHub Desktop.
Directory tree array
<?php
/**
* Creates a tree-structured array of directories and files from a given root folder.
*
* Gleaned from: http://stackoverflow.com/questions/952263/deep-recursive-array-of-directory-structure-in-php
*
* @param string $dir
* @param string $regex
* @param boolean $ignoreEmpty Do not add empty directories to the tree
* @return array
*/
function dirtree($dir, $regex='', $ignoreEmpty=false)
{
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string)$dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
$tree = dirtree($node->getPathname(), $regex, $ignoreEmpty);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
}
asort($dirs);
sort($files);
return array_merge($dirs, $files);
}
@yuri-ellfort
Copy link

If the directory name contains only numbers (for example, year), array_merge() will renumber the array, which is why the function will return an incorrect directory structure.

@nickorlov
Copy link

I have a big folders and files structure. Returns only 2 files without folders. $dir was like this: '/home/nick/project'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment