Reputation: 301
I'm trying to populate an array with only the file names ending in "mp4" with a recursive function looking through a list of sub-directories.
When I print the elements in the array with a foreach loop before I the return statement, the array displays all of the elements correctly. However, when I create a variable from the return of the method and try to iterate through it again, I only receive the last entry in the array.
Could this be caused by the recursion in the loop?
My code is as follows:
<?php
function listFolderFiles($dir){
$array = array();
$ffs = scandir($dir);
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
// This successfully adds to the array.
if(substr($ff, -3) == "mp4"){
$array[] = $ff;
}
// This steps to the next subdirectory.
if(is_dir($dir.'/'.$ff)){
listFolderFiles($dir.'/'.$ff);
}
}
}
// At this point if I insert a foreach loop,
// all of the elements will display properly
return $array;
}
// The new '$array' variable now only includes the
// last entry in the array in the function
$array = listFolderFiles("./ads/");
foreach($array as $item){
echo $item."<p>";
}
?>
Any help would be appreciated! I apologize for the sloppiness. I'm new to PHP.
Thanks in advance!
Upvotes: 0
Views: 820
Reputation: 888
you need to look into recursion more, your not passing the $array into the recursive calls so your actually only ever getting the first one back, the results of all subsequent calls are lost
if(is_dir($dir.'/'.$ff)){
listFolderFiles($dir.'/'.$ff);
}
the call to listFolderFiles needs to add those files to the current $array and that $array needs to be passed into subsequent calls. read more into recursion..
when your print line is active, it is getting called in every recursive call, not at the end.
Upvotes: 1
Reputation: 781741
When you recurse into the subdirectory, you need to merge its results into the array. Otherwise, the array only contains the matching files from the original directory, the matches from the subdirectories are discarded.
function listFolderFiles($dir){
$array = array();
$ffs = scandir($dir);
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
// This successfully adds to the array.
if(substr($ff, -3) == "mp4"){
$array[] = $ff;
}
// This steps to the next subdirectory.
if(is_dir($dir.'/'.$ff)){
$array = array_merge($array, listFolderFiles($dir.'/'.$ff));
}
}
}
// At this point if I insert a foreach loop,
// all of the elements will display properly
return $array;
}
Upvotes: 2