简体   繁体   中英

Remove folders from php scandir listing

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

Simple way

$dir = 'myfolder/';
$filelist = scandir($dir);
foreach ($filelist as $key => $link) {
    if(is_dir($dir.$link)){
        unset($filelist[$key]);
    }
}

If you know what the name of the folders are, you could create an array of these folders and then use array_diff to remove them from the result:

$folders = array('..', '.', 'folder');
$files = array_diff(scandir($dir), $folders);

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.

You can use the function glob() , and check if the item of array is_dir() .

scandir returns an array of folders. You can remove any element of the array like this:

unset( $filelist[0] );

where 0 is the index of the element you wish to remove. You can also use array_search() if you need to find directories by name.

try

<?php
$dir = "/example";

$filelist = new Array();
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if (!is_dir($file)) {
                $filelist[] = $file;
            }
        }
        closedir($dh);
    }
}
?>

It's like doing a scandir, but checking the type of the returned files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM