Search code examples
phpreaddir

printing 1 instead of filenames


I have some image collection in my specied directory.And i want to get their name using readdir() function.But instead of showing their names,it prints out a series of 1.How this can be done correctly ??I also want to know the reason for this behaviour

$dir='c:/xampp/htdocs/practice/haha/';
echo getcwd().'</br>';
if(is_dir($dir)){
echo dirname($dir);
     $file=opendir($dir);

     while($data=readdir($file)!==false){
        echo $data.'</br>';
     }

}

enter image description here


Solution

  • Operator precedence. This line:

     while($data=readdir($file)!==false){
    

    is being parsed/executed as

     while ($data = (readdir($file) !== false))
                    ^------------------------^
    

    Note the extra brackets. $data is getting the boolean TRUE result of the !== comparison. You need to rewerite as

     while(($data = readdir($file)) !== false){
           ^----------------------^
    

    That'll make $data get the string returned from readdir, and then that string will be compared with boolean false.

    Relevant docs: http://php.net/manual/en/language.operators.precedence.php