简体   繁体   中英

PHP case switch behaviour breaks a recursive scandir function

during my quest for some basic php knowledge , I tried to do a simple function to read files and dirs that will not use recursive iterators. (more of an exercise but actually needed for any php<5.3 servers)

the function works great - but when i tried to add a switch ($output) - it no longer lists all the files (for example, before adding the switch, it can see 61 files in 4 folders (3+root) but with the added switch it can only see 47 (only root) . am I doing something wrong here ? why does the switch statement break the faux "recursive-nest" ??

    function o99_list_my_files_scandir($dir,$output) 
    { 

        $result = $result2 = array(); 

        $root = scandir($dir); 

        foreach($root as $value) 
        { 

          if($value === '.' || $value === '..' || $value == 'Thumb.db' || $value == 'Thumbs.db' || $value == '') { continue;} 

            if(is_file("$dir/$value")) {$result[]="$dir/$value"; continue;} // array files
            if(is_dir("$dir/$value")) {$result2[]="$dir/$value"; continue;} // array dirs

            foreach(o99_list_my_files_scandir("$dir/$value") as $value) 

            { 
                $result[] = $value; 
            }
        } 
            // this is the troublemaker ...

            switch ($output) {
                case 'dirs' :
                return array_filter($result2);  // clean empty results of dirs
                break;

                case 'files' :
                return array_filter($result);   // Clean empty array of files
                break; 
            }

} 

is there any other simple way to get the function to return separate lists of dirs AND files and not a unified array ?

Because in this line...

foreach(o99_list_my_files_scandir("$dir/$value") as $value)

...you don't give $output to the recursively called function, so it won't output anything. Change it to:

foreach(o99_list_my_files_scandir("$dir/$value", $output) as $value)

Actually you should have gotten a warning about the missing argument.

You do not seem to set $output anywhere.

BTW: For learning purposes I strongly recommend adding error_reporting(E_ALL); as very first line of your script and re-run (first, without fixing anything), because you should have seen a warning as 2nd function parameter is not optional. You got signature

function o99_list_my_files_scandir($dir,$output) 

but call

o99_list_my_files_scandir("$dir/$value")

while you should

o99_list_my_files_scandir("$dir/$value", $output)

in your foreach()

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