I've written the below function, but fileList is blank when echoed out. Any ideas why this might be happening? and how to fix it?
function testing($dir){
echo $dir;
$fileList=array();
function recursiveScan($dir) {
$tree = glob(rtrim($dir, '/') . '/*');
if (is_array($tree)) {
foreach($tree as $file) {
if (is_dir($file)) {
echo $file . '('.filemtime($file).')'.'<br/>';
recursiveScan($file);
$fileList[date('YmdHis',filemtime($file))]=$file;
} elseif (is_file($file)) {
echo $file . '('.filemtime($file).')'.'<br/>';
$fileList[date('YmdHis',filemtime($file))]=$file;
}
}
?>
<pre>
<?php print_r($fileList);?>
</pre>
<?php
}
}
}
EDIT:
If I move the print_r bit of the code below up a few } then it outputs... but I want to output it once all directories have been searched through.
function recursiveScan($dir) {
$tree = glob(rtrim($dir, '/') . '/*');
if (is_array($tree)) {
foreach($tree as $file) {
if (is_dir($file)) {
echo $file . '('.filemtime($file).')'.'<br/>';
recursiveScan($file);
$fileList[date('YmdHis',filemtime($file))]=$file;
} elseif (is_file($file)) {
echo $file . '('.filemtime($file).')'.'<br/>';
$fileList[date('YmdHis',filemtime($file))]=$file;
}
}
}
?>
<pre>
<?php print_r($fileList);?>
</pre>
<?php
}
I think better approach will be to use the return value to function argument to get the results. Consider the following function:
function recursiveScan($dir, $fileList) {
$tree = glob(rtrim($dir, '/') . '/*');
if (is_array($tree)) {
foreach($tree as $file) {
if (is_dir($file)) {
$fileList = recursiveScan($file, $fileList);
} elseif (is_file($file)) {
$fileList[date('YmdHis',filemtime($file))]=$file;
}
}
}
return $fileList;
}
Now you can trigger the first call by doing something like:
$dir = "/"; // or from argument
$fileList = recursiveScan($dir, array());
After that, the $fileList
will contain list of the files