I have a php script $filelist = scandir('myfolder/')
which list outs files from my folder. But it is adding child folders also to the array so that they are also populated when i print the result using foreach
. I want to remove folders from getting added to the array. How can I do this??
The rmdir() function in PHP is an inbuilt function which is used to remove an empty directory. It is mandatory for the directory to be empty, and it must have the relevant permissions which are required to delete the directory.
The scandir() function returns an array of files and directories of the specified directory.
The scandir() function in PHP is an inbuilt function that is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.
Simple way
$dir = 'myfolder/';
$filelist = scandir($dir);
foreach ($filelist as $key => $link) {
if(is_dir($dir.$link)){
unset($filelist[$key]);
}
}
A clean concise solution could be to use array_filter to exclude all sub-directories like this
$files = array_filter(scandir('directory'), function($item) {
return !is_dir('directory/' . $item);
});
This effectively also removes the .
and ..
which represent the current and the parent directory respectively.
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