This is a simple PHP function to clean all the empty folders in a directory.
But it always takes the third element of the array as a directory, even if it's a file.
function myfunction($s){
echo "<br>Now the directory is $s";
echo "<br>";
if (is_file($s)) {
echo "$s is a file <br>";
return;
}
else {
echo "$s is a directory";
chdir($s);
$d = scandir(".");
echo "<br> Array elements are ". print_r($d) . "<br>";
echo sizeof($d);
for ($i= 2; $i <sizeof($d); $i++) {
$a = $d[$i];
echo "<br>Now the folder is $a <br>";
echo "<br>";
if (empty($a)) {
rmdir($a);
}
else{
myfunction($a);
chdir("..");
}
}
}
}
The function empty()
does no test a directory's content for emptiness, but only if the value of a variable is empty. Your variable $a
contains the file name of the current iteration, so you are testing whether or not a file has a file name. That will never happen, so you are always executing the branch with the recursive call.
You basically need to count the number of entries scandir()
returns for a directory. If the conut is 2
, the directory is empty and can be removed.