0

as you will see I'm a newbie

I have the following code:

while($file = readdir($dir)){
    if($file!="." && $file!=".."){
    $cont++;
        ...
        ...
     }
}

and next I want to work with the variable $file but if I do the this:

if($file){
    echo"OK";
}else{
       echo"Error";
}

I get ther Error message.

How can I work with the $file outside the while cycle??

Thanks

1
  • "$file outside the while" does not make sense. Which file exactly? Commented Oct 27, 2011 at 16:35

3 Answers 3

3

$file will be a boolean FALSE value when the loop exits. When readdir hits the end of the directory and has nothing more to read, it returns FALSE, which is assigned to your $file value.

As such, after the while() loop exits, $file will ALWAYS be false. If you want to preserve a particular filename for use outside the loop, you'll have to assign it to some other variable inside the loop:

while($file = readdir($dir)) {
   if ( ... ) { }
   $lastfile = $file;
}

...

With this, when the while() loop exits, $lastfile will have the filename of the last file returned by readdir.

Sign up to request clarification or add additional context in comments.

Comments

1

The $file is only existing inside the while loop.. Which is pretty obvious. Why would you want to use it outside of the loop? In that case anyway you'd just have the LAST $file. Possibility would be thus to declare a variable above the while loop, assign it inside the loop and use it after the loop.

$fix_file;

while($file = readdir($dir)){
    if($file!="." && $file!=".."){
        $cont++;
        $fix_file = $file;
        break;
     }
}

if ($fix_file)
     echo "OK";
else
     echo "Error";

1 Comment

It exists outside the loop as well. PHP's variable scope is function-level, not block-level. It's just that the while() sets it to false when readdir has nothing more to read.
0

What do you really want to test about $file - if it has any value at all? You can check this with the isset() or empty() functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.