Skip to content

Instantly share code, notes, and snippets.

@UziTech UziTech/glob_recursive.php

Last active Jul 28, 2020
Embed
What would you like to do?
Recursive glob search in php
/*
* License: DWTFYW
*/
function glob_recursive($base, $pattern, $flags = 0) {
if (substr($base, -1) !== DIRECTORY_SEPARATOR) {
$base .= DIRECTORY_SEPARATOR;
}
$files = glob($base.$pattern, $flags);
if ($files === false) {
$files = [];
}
foreach (glob($base.'*', GLOB_ONLYDIR|GLOB_NOSORT|GLOB_MARK) as $dir) {
$dirFiles = glob_recursive($dir, $pattern, $flags);
if ($dirFiles !== false) {
$files = array_merge($files, $dirFiles);
}
}
return $files;
}
@markparnaby

This comment has been minimized.

Copy link

markparnaby commented Jul 9, 2020

I add an extra line after line 10 as glob can return false, and your later array_merge should be fed an array. You catch the possible false return later on line 14, so that's good.

	$files = glob($base.$pattern, $flags);
	$files = $files !== false ? $files : [];
@UziTech

This comment has been minimized.

Copy link
Owner Author

UziTech commented Jul 9, 2020

I updated it, thanks! 💯

@WinterSilence

This comment has been minimized.

Copy link

WinterSilence commented Jul 28, 2020

function glob_recursive(string $baseDir, string $pattern, int $flags = 0)
{
    $flags |= GLOB_BRACE;
    $paths = glob(rtrim($baseDir, '\/') . DIRECTORY_SEPARATOR . $pattern, $flags);
    if ($paths) {
    	foreach ($paths as $path) {
           if (is_dir($path)) {
                $subPaths = (__FUNCTION__)($path, $pattern, $flags);
                if ($subPaths) {
                    array_push($paths, ...$subPaths);
                }
           }
    	}
    }
    return $paths;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.