Wednesday 27 June 2012

Difference between isset and empty in Php


Isset :
    1. isset checks to see if the variable have any value except NULL or not assigned a value.

    2. isset returns true, if that varibale exists and have value other than NULL.

    3. If variable assigned a value like " ", 0, "0" or FALSE are set. So, isset returns true.

Empty :

    1. EMPTY checks to see if a variable is empty.

    2. Empty is interpreted as : " " (an empty string), 0 (0 as an integer), 0.0 (0 as a float), "0" (0 as a string), NULL, FALSE, array() (an empty array), and "$var;" (a variable declared, but without a value in a class.

Some Examples :

1. $nullVar = NULL;

if ( isset($nullVar)) -- This would be FALSE
if ( empty($nullVar)) -- This is TRUE

2. $singleQuoteVar = '';
   $dblQuoteVar = "";

if ( isset($singlequoteVar)) -- This would be TRUE
if ( empty($singlequoteVar)) -- This is TRUE

if ( isset($dblquoteVar)) -- This would be TRUE
if ( empty($dblquoteVar)) -- This is TRUE

3. $zeroValue = 0;

if ( isset($zeroValue)) -- This would be TRUE
if ( empty($zeroValue)) -- This is TRUE

4. $TrueBoolValue = TRUE == 1;
$FalseBoolValue = FALSE == 0;

if ( isset($TrueBoolValue)) -- This would be TRUE
if ( empty($TrueBoolValue)) -- This is FALSE

if ( isset($FalseBoolValue)) -- This would be TRUE
if ( empty($FalseBoolValue)) -- This is TRUE

5. $arrVar = array():

if ( isset($arrVar)) -- This would be TRUE
if ( empty($arrVar)) -- This is TRUE