I finally found a solution :
echo "Only files\n";
$files = array_filter(glob("/*"), 'is_file');
var_dump($files);
But take care, array_filter will preserve numeric keys : use array_values if you need to reindex the array.
Domanda
I know that glob
can look for all files or only all directories inside a folder :
echo "All files:\n";
$all = glob("/*");
var_dump($all);
echo "Only directories\n";
$dirs = glob("/*", GLOB_ONLYDIR);
var_dump($dirs);
But I didn't found something to find only files in a single line efficiently.
$files = array_diff(glob("/*"), glob("/*", GLOB_ONLYDIR));
Works well but reads directory twice (even if there are some optimizations that make the second browsing quicker).
Soluzione
I finally found a solution :
echo "Only files\n";
$files = array_filter(glob("/*"), 'is_file');
var_dump($files);
But take care, array_filter will preserve numeric keys : use array_values if you need to reindex the array.
Altri suggerimenti
You can use GLOB_BRACE
to match documents against a list of known file extensions:
$files = glob("/path/to/directory/*.{jpg,gif,png,html,htm,php,ini}", GLOB_BRACE);
There is an easier way, just one line:
$files = glob("/path/to/directory/*.{*}", GLOB_BRACE);
the {*} means all file endings, so every file, but no folder!
10% faster compared to the solution of @AlainTiemblo, because it does not use an additional is_file
check:
$files = array_filter(glob("/*", GLOB_MARK), function($path){ return $path[ strlen($path) - 1 ] != '/'; });
Instead it uses the inbuild GLOB_MARK
flag to add a slash to each directory and by that we are able to remove those entries through array_filter() and an anonymous function.
Since PHP 7.1.0 supports Negative numeric indices you can use this instead, too:
$files = array_filter(glob("/*", GLOB_MARK), function($path){return $path[-1] != '/';});
No relevant speed gain, but it helps avoiding the vertical scrollbar in this post ^^
As array_filter()
preserve the keys you should consider re-indexing the array with array_values() afterwards:
$files = array_values($files);
Invert regexp do the job.
preg_grep(
';^.*(\\\\|/)$;',
glob("/*", GLOB_MARK),
PREG_GREP_INVERT
);
\\\\ is for Windows backslash 🤯🔫
This worked for me. if this helps anyone.
for file_name in glob.glob('**/*', recursive=True):
# we get all files and dirs
if os.path.isfile(file_name):
# we have only the files
$all = glob("/*.*");
this will list everything with a "." after the file name. so basically, all files.