Help with PHP array_filter function

Refer to the following function to scan files in a directory (taken from here )

function scandir_only_files($dir) { return array_filter(scandir($dir), function ($item) { return is_file($dir.DIRECTORY_SEPARATOR.$item); }); } 

This does not work because $ dir is not in the scope of the anonymous function and is displayed empty, forcing the filter to return FALSE each time. How can I rewrite this?

+6
source share
1 answer

You must explicitly declare variables inherited from the parent scope with the use keyword:

 // use the `$dir` variable from the parent scope function ($item) use ($dir) { 

 function scandir_only_files($dir) { return array_filter(scandir($dir), function ($item) use ($dir) { return is_file($dir.DIRECTORY_SEPARATOR.$item); }); } 

See this example on the anonymous functions page.

Closing can inherit variables from the parent scope. Any such variables must be declared in the function header. The parent region of the closure is the function in which the closure was declared (not necessarily the function from which it was called).

+15
source

Source: https://habr.com/ru/post/897102/


All Articles