I want to return multiple values from a PHP function, but it did not work as following codes:
The function is used to search the filenames in the specific folder and its recursive folders and store the filenames in the array.
In this example, the specific (main) folder is called: F:\test
The recursive folder is called: F:\test\subfolder
The main folder and subfolder carries 7 files, the filename formats are:
For main folder: 1.txt, 2.txt, 3.txt, 4.txt
For subfolder: 5.txt, 6.txt, 7.txt
function getDirectory( $path = '.', $level = 0 ) {
$i=0;$j=0;
$dh = @opendir( $path );
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory, this is what makes function recursive.
} else {
if ($level>0) //in a recursive folder
{
$dir_matched[$j]=$file;
$j++;
}
else //in main folder
{
$files_matched[$i] = $file;
$i++;
}
}
}
closedir( $dh );
//print_r ($files_matched);
//print_r ($dir_matched); I tested this before return, both works fine.
return array($files_matched,$dir_matched);
}
echo "<pre>";
list($a,$b) = getDirectory("F:\test");
print_r ($a); // this will result the same as array $files_matched, it ok!
print_r ($b); // but i don't know why I cannot get the array of $dir_matched??
echo "</pre>";
As you can see, it is so strange that I can only get one array only? Is there any idea I can get the contents of the $dir_matched array?
The way it is written now, you are not capturing the values from the recursive call. Within your function, on this line:
You need to capture the returned values from it. Something like:
$imay not what you want here, you’ll need to increment it here also like you do in yourelse statement, or else capture them in a different variable to reflect a subdirectory – depends on what you want to accomplish.