Page 1 of 1

What's the "FALSE" iteration of an array?

Posted: Sat Oct 26, 2002 8:39 am
by Bill H
I find PHP's flexibility in its handling of variables a little confusing at times.
(No, no, no. I'm not being critical.)

How, in the following function can I indicate by the return value that the file was not successfully opened?

Code: Select all

function listall($name)
{
     $f = fopen($name, "r");
     if ($f != FALSE)
     {    $a = fread($f, filesize($name));        // read the whole file
          fclose($f);
          $a = trim($a);
          $r = explode("~", $a);
          return $r;
     }
     else return ??????;
}
Then in the use of the function I can do something like this:

Code: Select all

if (listall($Filename))
      // do one thing
else  // do something different
To all the helpful people posting answers in this forum: thanks.

Posted: Sat Oct 26, 2002 8:45 am
by volka

Code: Select all

function listall($name) 
{ 
     $f = fopen($name, "r"); 
     if ($f != FALSE) 
     {    $a = fread($f, filesize($name));        // read the whole file 
          fclose($f); 
          $a = trim($a); 
          $r = explode("~", $a); 
          return $r; 
     } 
     else
          return FALSE; 
} 

if ( ($r = listall($Filename)) !== FALSE) 
      // do one thing 
else
      // do something different

Posted: Sat Oct 26, 2002 9:15 am
by Bill H
Thanks for your reply. I haven't tested your code yet, but I have no doubt it will work.
A few things for clarification:

1. I'd lost sight of the fact that a PHP function can return different types as well as different values.
You're saying return a string array if successful and an integer if not.
Very cool. You cannot do that in C language. The function type is predefined.

2. I am aware that the three-symbol operator (===) means "equal in type and in value."

But in C language the statement

Code: Select all

$r = listall($Filename)
would always evaluate as TRUE.
In PHP, am I correct in assuming from your code that it evaluates as the first operand (as assigned)?

3. The operator !== returns TRUE if the operands are of different type.
Does it also return TRUE if they are of the same type but different values?

Thanks.

Posted: Sat Oct 26, 2002 9:31 pm
by volka
  • it's returning either an array or a boolean, but yes, the possibility of returning various types is sometimes very nice but death to validation processes ;)
  • ($r = listall($Filename)) != value) is valid in C, too. Note the extra brackets, i.e.

    Code: Select all

    while( (c=getch()) != 27)
       putc(c);
  • ===, !== compare type and value. Think of it as combination of java instanceof and .equals()