user3287550 user3287550 - 3 months ago 10
PHP Question

Return an array of directories from glob function

I'm trying to return an array of directories available inside another directory from a single line of code without execute the foreach. For do this I actually use this code logic:

$dirs = array();
foreach(array_filter(glob('main_dir/language/*'), 'is_dir') as $dir)
{
$dirs[] = basename($dir);
}


now the problem's that I should have another array called
$dirs
and push the directory name inside it, I'm looking for a solution in one line that return an array, something like this:

return array_filter(glob('main_dir/language/*'), 'is_dir')


any idea?

Answer

You can use json_encode function:

return json_encode(array_map('basename', array_filter(glob('main_dir/language/*'), 'is_dir')));

And then you can get the array with the json_decode function.