Re: Testing if variable was set

From: Date: Thu, 17 May 2001 09:25:46 +0000
Subject: Re: Testing if variable was set
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-53193@lists.php.net to get a copy of this message
In article <ef83b7e4a11ef18ba78d1947d8e17c1e@news.php.net>, jord@theinternetone.co.uk (Jordan Elver) wrote: > if($var) { > // variable is here > } > > But I've noticed that a lot of people do: > > if(isset($var)) { > // variable is here > } > > What's the difference and which is the best way? Turn up error reporting to E_ALL, and you'll notice a difference. Set $var to FALSE, NULL, an empty string, or zero, and you'll notice a difference. "if($var)" tests for a true value "if($isset($var))" does what its name suggests The first option often can have a convenience value, where error_reporting is not at E_ALL and where lumping all "false" values together and all "true" values together is acceptable to you. Where you genuinely need to distinguish between a set vs. an unset variable, use isset(). Where you need to distinguish between unset, set-with-"false"-value, and set-with-"true"-value, use isset() followed by either empty() or !$var. Where you need to make even finer distinctions, use isset() followed by the === operator. (By putting the isset() test first, you avoid error messages: if the comparison fails that first "isset" test, then it never gets passed on to the next comparison, where an error message would have been generated by the attempt to do a comparison against an unset variable.) -- CC

« previous php.general (#53193) next »