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

JohnDivam @johndivam

About: Focus on delivering high-quality solutions. #Laravel . Wye Team

Joined:
Jul 11, 2023

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

Publish Date: Aug 26 '23
9 6

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

Comments 6 total

  • Given Ncube
    Given NcubeAug 26, 2023

    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

    • JohnDivam
      JohnDivamAug 27, 2023

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

  • Allester Corton
    Allester CortonAug 27, 2023

    Clearly

  • Shshank
    ShshankAug 27, 2023

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

  • Edenn Touitou
    Edenn TouitouAug 30, 2023

    You can also add in your examples :

    $var5 = false; //empty($var5) => true
    
    Enter fullscreen mode Exit fullscreen mode
Add comment