Home > Mobile >  Scandir in a Recursive function
Scandir in a Recursive function

Time:02-25

I'm trying to make a recursive function to display a directory tree with scandir().

I've tried the code below, but it keeps sending

Warning: foreach() argument must be of type array|object

What am I doing wrong?

$dir = scandir('.');

function scan($location) {
    
    foreach($location as $path) {

        if (is_dir($path)) {

            scan($path);
        }

        else {
            echo $path.'<br>';
        }
    }
}

scan($dir);

CodePudding user response:

scandir return . (this dir) and .. (parent dir) too. You should ignore them.

if ($path != '.' && $path != '..' && is_dir($path)){
    scan(scandir($path));
}

CodePudding user response:

In the first call, you send the result of scandir(), which is an array (or false). Then, in the recursive calls, you send a string.

Then, you need to take care about the result of scandir(). It returns . and .. : the current directory, and the parent directory.

Your code with scandir() inside the function:

function scan($location) 
{
    $dirs = scandir($location);
    foreach($dirs as $path) {

        if ($path == '.' || $path == '..') continue;
        
        if (is_dir($path)) {

            scan($path);
        }

        else {
            echo $path.'<br>'; // 
        }
    }
}

scan('.');

Also, you could take a look on the DirectoryIterator class and the FilesystemIterator class.

  • Related