Possible Duplicate:
Whats the difference between if(!Variable) and if(isset($variable)) ?
In Facebooks php API example they use if($var){ //do something }else{ //do something else} whick got me thinking about the difference of if($var) and if(isset($var)). The first sure looks neater but can I surely use it?
Difference between isset() and array_key_exists() Function: The main difference between isset() and array_key_exists() function is that the array_key_exists() function will definitely tells if a key exists in an array, whereas isset() will only return true if the key/variable exists and is not null.
Definition and Usage The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.
Definition and Usage The isset() function determines whether a variable is set. To be considered a set, it should not be NULL. Thus, the isset() function also checks whether a declared variable, array or array key has a null value. It returns TRUE when the variable exists and is not NULL; else, it returns FALSE.
isset() is best for radios/checkboxes. Use empty() for strings/integer inputs. when a variable contains a value, using isset() will always be true. you set the variable yourself, so it's not a problem.
Using
if ($var)
You'll test if $var
contains a value that's not false -- 1 is true, 123 is too, ...
For more informations about what is considered as true or false, you should take a look at Converting to Boolean.
Using isset()
, you'll test if a variable has been set -- i.e. if any not-null value has been written to it.
The difference is that the isset
will be true for any variable that has been declared/initalized to anything (besides null). the if($var)
is true for all values of var OTHER THAN those that evaluate to false (0, '', null, false, etc).
So the difference is for values that are not null, but still evaluate to false: 0, '' (empty string), false, empty array, etc.
Try this:
$var = ''; //or equivalently 0, false, ''
if(isset($var)) echo 'a';
if($var) echo 'b';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With