Search blog

Wednesday, September 14, 2016

Understanding the Difference Between isset(), empty(), is_empty() and unset() functions in PHP

isset() function in PHP: 

As the name suggests the isset() function in PHP checks whether the variable 'is set' or not. To be more clear this is what happens when this function is called:
  •  Returns TRUE if the variable exists; FALSE otherwise. In other words, only variable that don't exist (or, variable with strictly NULL values) will return FALSE in the isset() function. All variable types that have any type of value, whether it is 0, a blank text string, etc. will return TRUE.

empty() function in PHP: 

The empty() function in PHP returns TRUE or 1 in the following cases:
  1. if the variable is undeclared
  2. if the variable is assigned zero. Example $high = 0;
  3.  if the variable is assigned an Empty string or declared NULL. Example: $high= ''; or $high = NULL;

is_null() function in PHP:

As the name suggests, the is_null() function checks whether a variable is NULL or not. This holds TRUE if:
  1. variable is not declared
  2. variable is declared as NULL. Example: $high = NULL;
Note: '' empty string is not NULL because NULL has no memory allocation, as it has nothing to store, but an empty string does.


    You can wipe a variable out of existence using unset().

    Handy Usage: These functions are handy when you need to make sure that the user filled out the appropriate fields in the form.


      // Experimenting with isset(), empty() & is_null()   
     // Comment/Uncomment each condition below and test  
      // $high = '';   
      // $high = NULL;   
      // $high = 0;   
      // $high = 'hello';   
      echo '$high = '.$high.'<br />';   
      echo 'isset($high) = '.isset($high).'<br />';   
      echo 'empty($high) = '.empty($high).'<br />';   
      echo 'is_null($high) = '.is_null($high).'<br />';   

    >> Last Updated: 2-Mar-2018

    No comments:

    Post a Comment

    Thank you for your Feedback!

    Top 5 Posts (Weekly)