readdir

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

readdir

Post by shiznatix »

why is the 1st way more correct than the 2nd? the 2nd one works in this app that my coworker made so i am wondering why thats so wrong.

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";
   }
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post by raghavan20 »

you use !== or === when you want to compare whether the values are the same and of the same data type,
PHP Manual wrote: $a === $b; Identical TRUE; if $a is equal to $b, and they are of the same type. (introduced in PHP 4)
readdir() wrote: Returns the filename on success, or FALSE on failure.
you use !==, because you do not want to make decision on a string "false" because readdir returns string, rather you should compare with the boolean type value FALSE
shiznatix wrote: false !== ($file = readdir($handle)); //this returns TRUE
if "false" is returned, then it does not mean while condition is FALSE
if only FALSE is returned, then the while condition is FALSE

EDIT: The same example you presented, is in PHP Manual...I just saw it, here is their explanation
Please note the fashion in which readdir()'s return value is checked in the examples below. We are explicitly testing whether the return value is identical to (equal to and of the same type as--see Comparison Operators for more information) FALSE since otherwise, any directory entry whose name evaluates to FALSE will stop the loop (e.g. a directory named "0").
Post Reply