Wrox Home  
Search P2P Archive for: Go

  Return to Index  

pro_php thread: isset or just if


Message #1 by Paul <paul@d...> on Sun, 12 May 2002 02:44:42 -0400
> If I want to test for the existence of the variable $resetTest, which
> one of these methods is best?

isset is best because its does exactly what you're looking for.  It also
suppresses the undeclared variable warning when you're running php with
NOTICE level warnings displayed, so that in itself makes it a good choice to
use.

If() tests a boolean condition, and if the variable or expression contained
in the parens doesn't evaluate to a boolean, it's result is converted to a
boolean, which can have some unexpected effects if you're not careful.

For example, each of these values of $var:

$var = 0;
$var = '';
$var = "false";

outputs "ELSE block." in the following code:

if($var)
{
   echo "IF block.\n";
}
else
{
   echo "ELSE block.\n";
}

So it's misleading, because many developers assume that if a string is
nonempty, then it evaluates to true.

That's also why you'll notice that the "correct" way to loop through a
directory listing is given in http://www.php.net/dir.  If any of the
filenames you're looping through happens to be "false" or "0000" or
whatever, you'll break out of the loop prematurely.

Since isset() returns true or false, it lends itself to be used in a
conditional expression (like that required by if() ).


> Or if you've installed php on your computer and the if (); function is
undifined.

Please say that this is a joke...?  if isn't a function, it's a flow control
construct built in to the language.  If it's undefined, you've got more
serious problems than wondering if you should use isset() or not. =)

I think the safest thing to do is use a combination of isset() and another
conditional expression.

For example, if(isset($var) && ($var != '')) is the safest way to test
whether $var has a value.  Why?  Because of "lazy evaluation", if isset()
returns false, then $var != '' is not executed.  If you didn't include the
isset test, then $var != '' would've reported a NOTICE level warning that
you were using an uninitialized variable.


Take care,

Nik


  Return to Index