Search code examples
phparraysdirectorydir

is_dir not working as expected


I've got a problem when using is_dir while I iterate over all the files in a certain directory. The code is kind of small so I think you'll better understand what I mean if I post it:

 $files = array();

 if ($dir = @opendir($folder)){ 

    while($file = readdir($dir)){

      if (is_dir($file)) $files[] = $file;  
    }        
    closedir($dir);    
}
print_r($files)

It dumps: ( [0] => . )

Otherwise, if I don't check wether the file is a dir by using this code:

 $files = array();

if ($dir = @opendir($folder)){ 

    while($file = readdir($dir)){

      $files[] = $file;  
    }        
    closedir($dir);    
}
print_r($files)

It dumps what expected: ( [0] => .. [1] => bla [2] => blablabla [3] =>index.php [4] => styles.css [5] => . )

I guess it's just some noob problem with using the $file var as a parameter but don't know how to make it work.

Thanks for reading!


Solution

  • As Kolink said in the comments, you're probably better off going the glob route, but if you decide to stick with opendir:

    The path will be $folder . '/' . $file, not just $file. opendir() returns relative paths. So is_dir is returning false in your loop.

    if ($dir = opendir($folder)){ 
    
        while(false !== ($file = readdir($dir))) {
            if ($file == '.' || $file == '..') {
                continue;
            } else if (is_dir($folder . '/' . $file)) {
                $files[] = $file;
            }
        }   
    
        closedir($dir);    
    
    }
    

    Also, note the false !==. This is necessary because a folder named "0" would evaluate to false (or a few other edge cases). Also, you'll very rarely actually care about . and .., so that code is in there to filter . and .. out.