Reputation: 21406
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??
Upvotes: 7
Views: 19413
Reputation: 6810
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.
Upvotes: 7
Reputation: 111
Simple way
$dir = 'myfolder/';
$filelist = scandir($dir);
foreach ($filelist as $key => $link) {
if(is_dir($dir.$link)){
unset($filelist[$key]);
}
}
Upvotes: 11
Reputation: 91
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);
Upvotes: 4
Reputation: 1087
You can use the function glob(), and check if the item of array is_dir().
Upvotes: 4
Reputation: 3504
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
Upvotes: 0
Reputation: 28926
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.
Upvotes: 1