Skip to content

Instantly share code, notes, and snippets.

@yuri-ellfort
Forked from jasonhofer/directory-tree-array.php
Last active July 15, 2022 10:18
Show Gist options
  • Save yuri-ellfort/5ae0478b5e938c4eaf8e08dc433824c4 to your computer and use it in GitHub Desktop.
Save yuri-ellfort/5ae0478b5e938c4eaf8e08dc433824c4 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 $dirs + $files;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment