DEV Community

JohnDivam
JohnDivam

Posted on • Edited on

Comparing PHP functions: empty(), is_null(), isset().

It seems like there might be a few typos in your question, but I'll assume you're asking about comparing three PHP functions: empty(), is_null(), and isset(). These functions are used to check the status and value of variables in PHP. Let's discuss each function and their differences:

In summary:

  • Use empty() to check if a variable is considered empty, including null.
$var1 = "";      // Empty string  // empty($var1) => true
$var1 = "0";     // Empty string  // empty($var1) => true
$var2 = null;    // Null value    //  empty($var2) => true
$var3 = 0;       // Numeric zero  // empty($var3) => true
$var4 = array(); // Empty array   // empty($var4) => true

Enter fullscreen mode Exit fullscreen mode
  • Use is_null() to specifically check if a variable is null.
$var = null;  // is_null($var) => true
$var = 0;  // is_null($var) => false
$var = array();  // is_null($var) => false
Enter fullscreen mode Exit fullscreen mode
  • Use isset() to check if a variable is set and not null.
$var = null; // isset($var) => false
$var = "Hello"; // isset($var) => true
$var = 0;      // isset($var) => true
$var = array();  // isset($var) => true
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
slimgee profile image
Given Ncube

Thanks for clearing the confusion Johnny
I personally prefer to use empty() to check if an array or any iterable type has any elements in it

is_null() to check if a varaible is null. I rarely use isset() but comes very handy when checking a variable has been declared

Collapse
 
johndivam profile image
JohnDivam

Thank you Given Ncube! !
I'm glad you found it helpful.

Collapse
 
deozza profile image
Edenn Touitou

You can also add in your examples :

$var5 = false; //empty($var5) => true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
allestercorton profile image
Allester Corton

Clearly

Collapse
 
shshank profile image
Shshank

Nice post it will help other dev who faced confusion between empty and isset.

Collapse
 
johndivam profile image
JohnDivam

Thank you Shshank!