Search code examples
phparraysrecursion

PHP: Function not returning Array


Can someone help me out? I cannot see it. The function below is not returning the array. The print_r($list)(above the return) prints the array on the screen. But the print_r($files)returns an empty array....

function listFolderFiles($dir){
    $ffs = scandir($dir);
    $i = 0;
    $list = array();
    foreach ( $ffs as $ff ){
        if ( $ff != '.' && $ff != '..' ){
            if ( strlen($ff)>=5 ) {
                if ( substr($ff, -4) == '.mp4' ) {
                    $value = $dir.'/'.$ff;
                    $list[] = $value;
                }
            }
            if( is_dir($dir.'/'.$ff) )
                    listFolderFiles($dir.'/'.$ff);
        }
    }

    print_r($list);  // Returns the full array with values
    return $list;
}
$files = listFolderFiles($_POST['path']);
print_r($files) // Returns an empty array..... :(:(

Solution

  • Your recursion call doesn't handle the returned array:

    listFolderFiles($dir.'/'.$ff);
    

    You need to merge the array here:

    $list = array_merge($list, listFolderFiles($dir.'/'.$ff) );