0

I have been looking at a bunch of examples throughout Stack Overflow about getting a list of files recursively and storing them in a PHP array. Whatever it is that I am doing wrong is causing the array to be empty. Here is an portion of what I have.

<?php
$mediaFiles = array();
function getFiles() {
    $media = "./media";
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($media)) as $filename){
        if ($filename->isDir()) continue;
        $mediaFiles[] = $filename->getPathname();
    }
}
getFiles();
?>

Of course, that is part of it, and not all of it, but it is the relevant portion. I can't seem to figure out the issue, being that I am new to PHP. What am I doing wrong, or is there a better way to do this?

The folder it should be getting the files from has about 800 files in it. So it definitely should not be empty.

  • Do you mean ` – Zoe Edwards Mar 16 '18 at 14:13
  • 7
    Learn about [variable scope](http://php.net/manual/en/language.variables.scope.php). The `mediaFiles` on line 2 is not the same `mediaFiles` on line 7. – aynber Mar 16 '18 at 14:15
  • @ThomasEdwards That was a typo only in the question. `$mediaFiles[]` is later being converted into a json format and inserted into a javascript array. However, I found out that it is empty before it is converted, unless it is being converted too soon, which is possible. – Christian Sirolli Mar 16 '18 at 14:18
  • See @aynber’s comment, I think that’s probably it – Zoe Edwards Mar 16 '18 at 14:19
  • The php was fine, it was just the order the php loaded in reference to the whole document that was causing issues mixed with variable scope. – Christian Sirolli Mar 16 '18 at 14:34

0 Answers0