Question

$files = array();

function listFolderFiles($dir){
    $ffs = scandir($dir);
    echo '<ol>';

    foreach($ffs as $ff){
        if($ff != '.' && $ff != '..'){
            if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
            else echo '<li>'.$ff;

            array_push($files, array('file' => $dir.'/'.$ff, 'hash' => hash_file('md5', $dir.'/'.$ff)));
            echo '</li>';
        } 
    }
    echo '</ol>';
}

listFolderFiles('/var/www');
var_dump($files);

Why i'm getting empty output here?

array(0) { };
Was it helpful?

Solution

This is a scope issue. Your $files array variable is outside of your function.

You need to pass that as a parameter as a reference (Tipped by @Barmar ;) ) to it..

The right way..

function listFolderFiles($dir,&$files){

and call it like.. listFolderFiles('/var/www',$files);

You are passing it as a reference because you are not returning the array , so whatever changes done inside the function to the array will remain there itself. So you need to add reference as shown in the method signature. This will modify the original array itself.

OTHER TIPS

You can pass a variable by reference, as in Shankar's answer. Or you can have the function return a result:

$files = listFolderFiles($dir);    

function listFolderFiles($dir){
    $files = array();
    $ffs = scandir($dir);
    echo '<ol>';

    foreach($ffs as $ff){
        if($ff != '.' && $ff != '..'){
            if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
            else echo '<li>'.$ff;

            array_push($files, array('file' => $dir.'/'.$ff, 'hash' => hash_file('md5', $dir.'/'.$ff)));
            echo '</li>';
        } 
    }
    echo '</ol>';
    return $files;
}

For you purposes here, it may be better to declare the files variable inside the function itself, and return it at the end. This way, the function will be re-usable:

function listFolderFiles($dir){
    $files = array();
    $ffs = scandir($dir);
    echo '<ol>';

    foreach($ffs as $ff){
        if($ff != '.' && $ff != '..'){
            if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
            else echo '<li>'.$ff;

            array_push($files, array('file' => $dir.'/'.$ff, 'hash' => hash_file('md5', $dir.'/'.$ff)));
            echo '</li>';
        } 
    }
    echo '</ol>';
    return $files;
}

$files = listFolderFiles('/var/www');
var_dump($files);

you can use globals

function listFolderFiles($dir){

global $files; // global var

    $ffs = scandir($dir);

    echo '<ol>';
    foreach($ffs as $ff){

        if($ff != '.' && $ff != '..'){

            if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
            else echo '<li>'.$ff;
            array_push($files, array('file' => $dir.'/'.$ff, 'hash' => hash_file('md5', $dir.'/'.$ff)));
            echo '</li>';

        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top