Skip to content

Instantly share code, notes, and snippets.

@peledies
Created April 13, 2017 16:05
Show Gist options
  • Save peledies/05d946f1125ae47a9a90a4fe1accccb1 to your computer and use it in GitHub Desktop.
Save peledies/05d946f1125ae47a9a90a4fe1accccb1 to your computer and use it in GitHub Desktop.
/**
* [A function to build an array from a provided directory path]
* @param \DirectoryIterator resource
* @param array or null
* @param array or null
* @param boolean or null (default = false)
*
* @return array
*/
function DirectoryIteratorToArray(\DirectoryIterator $it, $file_exclude = ['.DS_Store'], $directory_exclude = [], $fullpath=false) {
$file_exclude = (is_array($file_exclude))? $file_exclude : [$file_exclude];
$directory_exclude = (is_array($directory_exclude))? $directory_exclude : [$directory_exclude];
$result = array();
foreach ($it as $key => $child) {
if ($child->isDot()) {
continue;
}
if ($child->isDir()) {
$subit = new \DirectoryIterator($child->getPathname());
if(!in_array($child->getBasename(), $directory_exclude)){
$result[$child->getBasename()] = DirectoryIteratorToArray($subit, $file_exclude, $directory_exclude, $fullpath);
}
} else {
if(!in_array($child->getBasename(), $file_exclude)){
$result[] = ($fullpath)? $child->getPathname() : $child->getBasename();
}
}
}
return $result;
}
$directories = DirectoryIteratorToArray(new \DirectoryIterator($directory), null, null, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment