Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove folders from php scandir listing

Tags:

php

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??

like image 1000
Alfred Avatar asked Jun 08 '11 17:06

Alfred


People also ask

How do I empty a directory in PHP?

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.

How do I get a list of files in a directory in PHP?

The scandir() function returns an array of files and directories of the specified directory.

What is Scandir PHP?

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.


2 Answers

Simple way

$dir = 'myfolder/';
$filelist = scandir($dir);
foreach ($filelist as $key => $link) {
    if(is_dir($dir.$link)){
        unset($filelist[$key]);
    }
}
like image 93
Stéphane Comte Avatar answered Oct 05 '22 06:10

Stéphane Comte


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.

like image 20
Niket Pathak Avatar answered Oct 05 '22 07:10

Niket Pathak