Stumped by this one:
I have a function that returns an array of folders in a given directory. When I iterate through the array, I can see all the items. However, if I try to print the first item, I get nothing:
function get_folders($dir) {
return array_filter(scandir($dir), function ($item) use ($dir) {
return (is_dir($dir.'/'.$item) && $item != "." && $item != "..") ;
});
}
$folders = get_folders(".");
$first_folder = $folders[0];
echo $first_folder; // returns blank.
Interestingly, if I don’t filter out the “.” and “..”, then $first_folder does print “.”. Can anyone explain this?
From the array_filter manual:
So,
scandir($dir)gets you an array with.at key0, thus if you later filter.out, there will be nothing at key0in the result.If you want to know what the first key of the resulting array is, try the
array_keysfunction.EDIT: actually, salathe’s suggestion to use
array_valuesis better in your case than getting the keys fromarray_keys.