Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between if(isset($var)) and if($var) [duplicate]

Tags:

php

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?

like image 332
Joseph Avatar asked Apr 16 '11 20:04

Joseph


People also ask

What's the difference between isset () and Array_key_exists ()?

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.

What is the isset () function used for?

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.

Does Isset check for NULL?

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.

Should I use isset?

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.


2 Answers

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.

like image 173
Pascal MARTIN Avatar answered Oct 13 '22 07:10

Pascal MARTIN


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';
like image 45
jon_darkstar Avatar answered Oct 13 '22 08:10

jon_darkstar