简体   繁体   中英

Remove files from an array of files and directories using PHP

I'm trying to get a list of directories in a path by using scandir and removing the files from the array but I'm getting errors from my echo.

I'm using the code

$path = "Calltypes/";
$files = scandir($path);
$files = array_diff(scandir($path), array('.', '..'));

for($i = 0; $i < sizeof($files); $i++) {
    if(!is_dir($files[$i]))
        array_splice($files, $i, 1);
}

echo sizeof($files);

This is the echo output:

Notice: Undefined offset: 0 in C:\xampp\htdocs\index.php on line 32
2

The Calltypes/ path has 3 folders and 1 txt file.

Edit: line 32 is

if(!is_dir($files[$i]))

You can use foreach instead of for . After that use unset because array_splice will rearrange keys so you will get errors

$path = "Calltypes/";
$files = scandir($path);
$files = array_diff(scandir($path), array('.', '..'));

foreach ($files as $key => $value) {
    if(!is_dir($path.$files[$key]))
       unset($files[$key]);
}
echo sizeof($files);

In your case, Notice: Undefined offset: 0 occurs because arry_diff returns an array containing all the entries from the 1st array without reindexing . That means, that $files array would not have 0 index after array_diff processing.

Instead of "splicing" array items while iterating in the loop - use array_filter to get only directory names:

$path = "Calltypes/";
$files = scandir($path);
$files = array_diff(scandir($path), array('.', '..'));

$files = array_filter($files, "is_dir");

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