KirKu
KirKu

Reputation: 5

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

Upvotes: 0

Views: 975

Answers (2)

inetphantom
inetphantom

Reputation: 2617

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 ++.

Upvotes: 0

Amarnasan
Amarnasan

Reputation: 15529

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.

Upvotes: 4

Related Questions