'Scandir in a Recursive function

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);


Solution 1:[1]

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.

Solution 2:[2]

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Syscall
Solution 2 amiad