Behavior isset, empty and casting of a variable as boolean in if statement

Suppose you want to check a variable is available or not. Then we can use the following

1. using isset:

if(!isset($var)){

//do something

} else{

//do something

}

2. Using empty:

if(!empty($var)){

//do something

} else{

//do something

}

3. Using the Implicit casting facility

if($var){

//do something

} else{

//do something

}

Now explanation and others

1. the isset function just check only if the variables is set(defined/declared) or not. If defined then return true else return flase. But this don’t check that the variable has a value or empty. So you should be careful to use this function. example:

isset($var);// this will return false

—————-

$var =  ‘test’;

isset($var);//this will return true

———-

$var = ”;

isset($var) //this will also return true

2. if u use empty then
Returns FALSE if $var has a non-empty and non-zero value.

The following things are considered to be empty:

“” (an empty string)
0 (0 as an integer)
“0″ (0 as a string)

and this is an opposite of (boolean)$var.

3.  Casting of the variable

if you use the casting then it will work as empty method but warning is generated when the variable is not set.

****As of PHP 5, objects with no properties are no longer considered empty

Leave a Comment