Search code examples
phpfunctionscope

array_push() not affecting array defined outside of function scope


$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 am I getting empty output here?

array(0) { };

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.