I have a recursive function that is supposed to print the contents of a directory. Here is the code
function dirs($dir, $tab) {
$d = opendir($dir);
while ( ($name = readdir($d)) !== false ) {
if ( $name == "." or $name == ".." ) continue;
if ( is_dir($dir . '/' . $name) ) {
echo "<b>" . $tab . "[$name]</b><br>";
$tab .= "-";
dirs($dir . '/' . $name, $tab);
}
else {
echo $tab . $name . '<br>';
}
}
closedir($d);
}
dirs("C:/php5", "");
The output for this function wuld be like that ([extras] is empty directoty):
[dev]
-php5ts.lib
-[ext]
--php_bz2.dll
--php_curl.dll
--php_enchant.dll
--php_exif.dll
--etc.
--[extras]
---glib-2.dll
---gmodule-2.dll
---icudt.dll
---icudt46.dll
---icuin.dll
---etc.
but not like that
[dev]
-php5ts.lib
[ext]
-php_bz2.dll
-php_curl.dll
-php_enchant.dll
-php_exif.dll
-etc.
[extras]
glib-2.dll
gmodule-2.dll
icudt.dll
icudt46.dll
etc.
The question is why does “$tab” behave as a global variable and not as a local one?
Thanks in advance.
The problem is that you are actually re-assigning the value of the local copy of
$tab, whereas what you actually want to be doing is passing$tab.'.'to the next iteration.Because you have re-assigned it, it will continue to have the new value in the outer iteration after the inner iteration has executed.
Change:
to simply: