Alain Tiemblo Alain Tiemblo -4 years ago 145
PHP Question

Is there a way to glob() only files?

I know that

can look for all files or only all directories inside a folder :

echo "All files:\n";
$all = glob("/*");

echo "Only directories\n";
$dirs = glob("/*", GLOB_ONLYDIR);

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).

Answer Source

I finally found a solution :

echo "Only files\n";
$files = array_filter(glob("/*"), 'is_file');

But take care, array_filter will preserve numeric keys : use array_values if you need to reindex the array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download