Page 1 of 1

the correct way to loop over a directory

Posted: Thu Jul 20, 2006 2:28 pm
by fgomez
Hello,

On http://us3.php.net/manual/en/function.readdir.php I saw this:

Code: Select all

/* This is the correct way to loop over the directory. */
   while (false !== ($file = readdir($handle))) {
       echo "$file\n";
   }

   /* This is the WRONG way to loop over the directory. */
   while ($file = readdir($handle)) {
       echo "$file\n";
   }
Can anyone explain to me why this is?

Thanks!

Posted: Thu Jul 20, 2006 2:35 pm
by daedalus__
$file is always going to equal readdir() because readdir is always going to return a value. whether that value is true or false is what you need to know.

Posted: Thu Jul 20, 2006 2:38 pm
by fgomez
So would the "wrong way" create an infinite loop?

Posted: Thu Jul 20, 2006 2:39 pm
by daedalus__
im assuming it would, but im not going to test it lol

Posted: Thu Jul 20, 2006 2:44 pm
by wtf
If you're using PHP5 you should check into DirectoryIterator

Posted: Thu Jul 20, 2006 2:46 pm
by MrPotatoes
Daedalus- wrote:im assuming it would, but im not going to test it lol
i've broken the video driver on my computers running an infinate while loop and being too late to stop it. nothing to do but pull the cord or restart. it's the worst and stupidest thing *sigh*

Posted: Thu Jul 20, 2006 2:58 pm
by fgomez
Thanks for the tip, wtf.

Interesting... this code I've inherited uses the "wrong way" but doesn't seem to go into an infinite loop.

I guess my larger question is whether this type of syntax:

Code: Select all

while ($file = readdir($handle)) { /*do something*/}
should always be avoided... For instance I use this syntax a lot:

Code: Select all

while(list($var2, $var2) = mysql_fetch_row($result)) { /*do something*/}
Should I instead be writing:

Code: Select all

while (false !== (list($area_name, $city_name) = mysql_fetch_row($result)) { /*do something*/}
???

Posted: Thu Jul 20, 2006 3:10 pm
by RobertGonzalez
It depends on what you are comparing. The syntax === or !== is not just checking equality, it is checking type as well.

Posted: Thu Jul 20, 2006 3:14 pm
by fgomez
I've read a little about === and !==. I guess I better look into it in a little more depth. Thanks!

Posted: Thu Jul 20, 2006 4:12 pm
by AngryPanda
The reason why it is wrong is because if a file happened to be named "false" or something. $file would be set to "false" (the name of the file) and the if() statement would incorrectly assume that the directory has no more files left. That's why the === (strict) operator is used as someone else explained. That way, the if() statement will correctly allow for files named "0" or "false" or whatever else the parser interprets as a false value.

Posted: Fri Jul 21, 2006 12:14 am
by feyd
list() = mysql_* should be avoided, actually. Why? When the fetching functions run out of records to return what does it return? A single value, not an array.