Is there a way to glob() only files?

后端 未结 5 1357
逝去的感伤
逝去的感伤 2020-12-30 21:34

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 d         


        
5条回答
  •  伪装坚强ぢ
    2020-12-30 21:43

    10% faster compared to the solution of @AlainTiemblo :

    $files = array_filter(glob("/*", GLOB_MARK), function($path){ return $path[ strlen($path) - 1 ] != '/'; });
    

    It uses GLOB_MARK 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 stackoverflow scrollbar ^^

    As array_filter() preserve the keys you should consider re-indexing the array with array_values() afterwards:

    $files = array_values($files);
    

提交回复
热议问题