Invalid argument supplied for foreach() - using glob

前端 未结 3 1150
深忆病人
深忆病人 2021-01-23 16:42

Today i have a problem with my script, my script should search for (.css files)

I\'ve used a code to:

  1. Search for all subfolders in a root folder
相关标签:
3条回答
  • 2021-01-23 16:58

    You say you are sure that your array is not empty, but what the Invalid argument supplied for foreach() error message means is that it is not even an array. Try it youself if you don't believe it:

    var_dump($add);
    

    Most likely, there was an error finding files and glob() is returning FALSE:

    Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

    0 讨论(0)
  • 2021-01-23 17:09

    Change this:

    $path[] = $dir;
    foreach($path as $dirname){
        $add = glob($dirname . '/*.css');
        foreach($add as $file){
    

    to this:

    $path[] = $dir;
    var_dump($path);
    foreach($path as $dirname){
        $add = glob($dirname . '/*.css');
        var_dump($add);
        foreach($add as $file){
    

    We don't know which line 131 is, so I don't know which foreach fails.

    (I'm guessing the 2nd, because the first is practically forced to array by $path[] = ..)

    0 讨论(0)
  • 2021-01-23 17:20

    I found the same issue with a PHP script today and it took switching from a foreach loop to a for loop to fix it. Not sure what means, the array looks and works the same.

    // Errors out
    $files = glob($directory.'*.html');
    foreach($files as $file){
        echo($file);
    }
    
    // No error
    $files = glob($directory.'*.html');
    for($i=0; $i<count($files); $i++){
        echo($files[$i]);
    }
    
    0 讨论(0)
提交回复
热议问题