简体   繁体   中英

counter in a php recursive function

I've looked thru the questions already with the system, but couldn't find the answer to my problem. I want to try a counter in a php recursive function, which looks for and deletes empty folders. I paste below a way to echo non-empties as "–" and empties as "|". It looks ok after all, but in case there's a lot to purge, it all grows into gibberish on the screen. Instead I'd like to see the numbers of folders checked vs deleted. Here's the code compiled so far using StackOverflow too. Any help pls?

function RemoveEmptySubFolders($path) {
    echo "–";
    $empty = true;
    foreach ( glob ( $path . DIRECTORY_SEPARATOR . "*" ) as $file ) {
        if (is_dir ( $file )) {
            if (! RemoveEmptySubFolders ( $file ))
                $empty = false;
        } else {
            $empty = false;
        }
    }
    if ($empty) {
        if (is_dir ( $path )) {
        // echo "Removing $path...<br>";
        rmdir ( $path );
        echo "|";
        }
    }
    return $empty;
}

Just pass the variables as reference:

function recursive($path, &$directories, &$removed) {
    echo "-";
    $directories ++;
    $empty = true;
    foreach ( glob ( $path . DIRECTORY_SEPARATOR . "*" ) as $file ) {
        if (is_dir ( $file )) {
            if (! recursive ( $file, $directories, $removed ))
                $empty = false;
        } else {
            $empty = false;
        }
    }
    if ($empty) {
        if (is_dir ( $path )) {
            $removed++;
            echo "|";
        }
    }
    return $empty;
}

$path = "c:\exampledir";
$directories = 0;
$removed = 0;
recursive($path, $directories, $removed);
echo("<br>$directories, $removed");

You could also use global variables, but that's very ugly, and every time you use a global variable othen than the standard ones, a kitty dies.

Object-Oriented variant:

Put everything in a class and add the instance attributes $checked and $deleted , then increment them with a selfmade procedure or (nasty code) just with += 1 or $var ++ .

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