Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with PHP array_filter function

Please see the following function to scan the 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 the $dir is not in scope in the anonymous function, and shows up empty, causing the filter to return FALSE every time. How would I rewrite this?

like image 893
Yarin Avatar asked Sep 11 '11 19:09

Yarin


People also ask

How do you filter an array key?

Filtering a PHP array by keys To use the PHP array_filter() function to filter array elements by key instead of value, you can pass the ARRAY_FILTER_USE_KEY flag as the third argument to the function. This would pass the key as the only argument to the provided callback function.

What is Array_map function in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.

Is array an element in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


1 Answers

You have to 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 from the anonymous functions page.

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

like image 114
Arnaud Le Blanc Avatar answered Oct 30 '22 02:10

Arnaud Le Blanc