Page 1 of 1

readdir

Posted: Fri Jan 20, 2006 4:57 am
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";
   }

Posted: Fri Jan 20, 2006 5:42 am
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").