I would like to pass in an array that contains a list of directories to scan. I want to iterate over each directory and push its content into another array that I will print out, but for some reason my code is not working. The directories exist and the path is correct. I think it has something to do with how I'm using foreach.
These are the errors I'm getting:
Notice: Undefined index: C:\Users\john\Desktop\files\images\ in C:\xampp\htdocs\test.php on line 6
Warning: scandir(): Directory name cannot be empty in C:\xampp\htdocs\test.php on line 6
This is the code:
function test($dir = []) {
foreach($dir as $bar) {
$list = [];
array_push($list, scandir($dir[$bar]));
}
print_r($list);
}
test(["C:\Users\john\Desktop\files\images\\", "C:\Users\john\Desktop\files\images\autumn\\"]);
If anyone can think of a simpler way to do this, please don't hesitate to tell me.
foreachis not like JavaScript'sfor instatement;$barwill be the actual element, not the element's key.$dirlook like?foreach($dir as $bar) { $list = []; array_push($list, scandir($bar)); }- would that be correct?$listwith each directory. Move$listout of theforeach.scandir($bar)and append the result to $list using array_merge(). In your current form, you are resetting the content of the list each iteration. Note that if you wanted to iterate over keys and values, there is theforeach ($array as $key => $value)syntax, but I don't think there's any need for that here.