Reputation: 885
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
Upvotes: 0
Views: 101
Reputation: 26380
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.
Upvotes: 0
Reputation: 7213
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";
Upvotes: 1
Reputation: 360572
$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.
Upvotes: 3