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?
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With