When to use isset(), empty(), and is_null() in PHP

| ,

I’ll be honest: most of the posts that I write are either because I’ve solved a problem for a client, or because I solved a problem that Past-david created. This is one of those PD problems, where I wrote some code that stopped functioning. When I looked into it, it turns out that I was using the wrong function to test for a variable in PHP.

There are a variety of functions made to test the state and value of variables, including ones that can tell you if there is anything available to use at all. Three of these functions that are easy to mix up are isset(), empty(), and is_null().

Built-in Variable Testing Tools

All three of these functions are built into PHP, so they should always be available for your use when writing code. empty() and isset() are language constructs, while is_null() is a standard function. We’ll go over why that’s important later in the article.

Before I discuss the difference and show a few examples, here are the descriptions for empty(), isset(), and is_null() from the php.net manual.

empty()

empty ( mixed$var ) : bool

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

isset()

isset ( mixed$var [, mixed$... ] ) : bool

Determine if a variable is set and is not NULL.

If a variable has been unset with unset(), it will no longer be set. isset() will return FALSE if testing a variable that has been set to NULL. Also note that a null character (“\0”) is not equivalent to the PHP NULL constant.

If multiple parameters are supplied then isset() will return TRUE only if all of the parameters are set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.

is_null()

is_null ( mixed$var ) : bool

Finds whether the given variable is NULL.

What’s the difference between these variable testing functions?

You can see from the above definitions that these three functions do similar, but not the same things. You’ve gotta determine if you’re trying to test for whether a variable is null, true or false, and whether the variable has been declared.

When to use empty()

If you are using empty() you can test if a variable is false, but also if the variable does not exist. This function is best used when you want to ensure both that the variable exists, and has a value that does not equal false. Note that PHP will treat empty strings, integers of 0, floats of 0.0, empty arrays, and the boolean value of false as false. So basically, only use empty() when you want to ensure that there is some actual value to the variable.

Since you don’t have to declare variables before using them in PHP, you can get in a position where you are trying to perform actions or run other tests on a variable that hasn’t yet been declared. While it’s best practice to declare your variables before use for this and other reasons, this gotcha is one of the reasons that empty() is used differently from isset().

When to use isset()

If you are using isset(), you can test specifically if the variable has been declared already, and that the value is not null. So as long as you have a declared variable that has a value set and is not of the value NULL, you’ll return true when you test it with isset(). This would be a good condition to check before doing other checks to perform actions on a variable:

// Declaring our variable
$variable = 'Some String';

// Testing that our variable exists, then testing the value
if ( isset( $variable ) && $variable !== 'Some Other String' ) {
    echo 'This code evaluates since both of the above are true';
}

In the above example, we’ve declared our variable as a string, then tested if the variable is set (it is), and if it is not equal to a different string (it is not). Since both of those tests are true, we would then echo out the sentence in that conditional statement.

Should you use is_null()?

Finally, is_null() works in a similar manner to isset() as its opposite, with one key difference: the variable must be declared to return true, provided that it is declared without any value, or is declared specifically as NULL.

I said above that isset() tests whether a variable has been set or not, which is true, but it can handle no variable being set and providing an output of false. That is helpful if somewhere else in the code the unset() construct has been used to remove a variable from scope entirely.

In contrast, is_null() would not only not properly evaluate, it would also return a notice due to its inability to evaluate. Usually that’ll look something like this:

Notice:  Undefined variable: variable in /directory/to/code.php on line X

Since isset() is both a language construction, and can handle variables that aren’t declared, I’d generally recommend it over using is_null() in any situation. If you need to use is_null(), I might suggest finding a way to rewrite your code instead.

Language Construct vs. Built-In Function

I mentioned before that isset() and empty() are both language constructs in PHP, where is_null() is a built in function. Language constructs are reserved keywords that can evaluate whatever follows them in a specific manner. That means that it already knows what to do without having to find the definition of the construct like it would a function.

The main things to keep in mind between the two when evaluating your code is that language constructs in PHP are slightly faster (but honestly not enough to worry about for speed optimization), they can’t be used in variable functions, and they don’t throw any errors when evaluating variables that don’t exist.

Many times I see warnings and notices because a variable hasn’t been declared, and no one has confirmed that the variable already exists before trying to do some other conditional check with it. Using isset() and empty() can go a long way to avoiding those errors.

Examples of output of these three functions

The following table has been taken directly from a demo created by Virendra Chandak on his personal site. You can view the demo here.

Value of variable ($var)isset($var)empty($var)is_null($var)
“” (an empty string)bool(true)bool(true)bool(false)
” ” (space)bool(true)bool(false)bool(false)
FALSEbool(true)bool(true)bool(false)
TRUEbool(true)bool(false)bool(false)
array() (an empty array)bool(true)bool(true)bool(false)
NULLbool(false)bool(true)bool(true)
“0” (0 as a string)bool(true)bool(true)bool(false)
0 (0 as an integer)bool(true)bool(true)bool(false)
0.0 (0 as a float)bool(true)bool(true)bool(false)
var $var; (a variable declared, but without a value)bool(false)bool(true)bool(true)
NULL byte (“\ 0”)bool(true)bool(false)bool(false)
Fediverse reactions

9 responses to “When to use isset(), empty(), and is_null() in PHP”

  1. Kara Franco Avatar

    Moral of the story: don’t use is_null() ! Thanks for writing and sharing, david. 🙂

  2. When programming, it can be important to check if a variable has been declared in memory and if it has a value before using the variable. This may seem unnecessary because a developer can just declare a variable and assign it a value before using the variable. However, as developers we often need to uses variables with assigned values coming from outside sources from the specific code we are writing. Examples of outside sources to receive variables from are an API, data POSTed from a form, query parameters from a URL, or results from a SQL query.

    The below screenshot shows an attempt to use an undefined variable in a PHP shell by echoing it. The result is a “PHP Notice: Undefined variable” error is displayed.

    In PHP, isset() is a language construct that is used to check if a variable has been declared and that the variable’s value is not NULL.

    Syntax: isset($var1 [, $var2 ...]);

    Output: isset() will return FALSE when checking a variable that has not been declared or if the variable has a value of NULL. isset() will return TRUE if the variable has been declared and has a value other than NULL.

    Using Multiple Parameters: Multiple variables can be checked with isset() by separating them with commas. When using isset() to check multiple parameters TRUE will only be returned if all variables are considered set.

    Results Of isset()

    The PHP interactive shell can be used to quickly see if the results of using isset() are true or false. The PHP interactive shell can be accessed by typing php -a at the command line.

    Result Of Checking A Defined Variable With isset()

    The below screenshot from a PHP interactive shell shows a variable named $str being declared and then assigned the string “Hello World”. The screenshot then shows var_dump() being used to display the data type and value of the result of isset($str).

    Result Of isset($str): true

    The $str variable has been declared and has a value other than NULL so true is returned.

    Result Of Checking An Undefined Variable With isset()

    The below screenshot shows var_dump() being used to display the data type and value of the result of isset($undeclared). In this example, the $undeclared variable has not been declared to the PHP interpreter before attempting to be used.

    Result Of isset($undeclared): false

    The $undeclared variable has not been declared to the PHP interpreter so false is returned.

    Result Of Checking An Unset Variable With isset()

    The below screenshot shows a variable named $str being declared and then assigned the string “Hello World”. The screenshot then shows var_dump() being used to display the data type and value of the result of isset($str). The unset() function is then used to destroy the $str variable. The screenshot then shows var_dump() being used to display the data type and value of the result of isset($str).

    Result Of isset($str) After unset(): false

    Running unset($str) destroys the $str variable so at this point in the run time of the PHP application the $str variable is undeclared in memory so false is returned.

    Result Of Checking NULL Variable With isset()

    The below screenshot shows a variable named $var being declared and then assigned the value null. The screenshot then shows var_dump() being used to display the data type and value of the result of isset($str).

    Result Of isset($var): false

    The isset() function checks if the variable is declared. In this case it is. isset() then checks the variable’s value. This variable has a value of NULL so the variable is not set in PHP and false is returned.

    Result Of Checking Array Offset With isset()

    The below screenshot shows a variable named $arr being declared and assigned an array of [0, 1, 2]. The screenshot then shows var_dump() being used to display the data type and value of the result of isset($arr[3]).

    Result Of isset($arr[3]): false

    The indexed array has offsets declared and values assigned for $arr[0], $arr[1], and $arr[2]. The offset for $arr[3] is not declared so false is returned.

    Results Of Checking Properties Of An Object With isset()

    The below screenshot shows a class Person being created with properties $fName and $lName. No values are assigned to the properties when the class is created. The $person variable is then declared and assigned an instance of the Person class. The screenshot then shows var_dump() being used to display the data type and value of the result of isset($person->fName).

    Result Of isset($person->fName): false

    The instance of the Person class has a property fName that has been declared, but no value has been assigned to it. The value of the fName property is actually NULL so false is returned.

    The below screenshot shows the same $person variable having the fName property set to the string “John”. The screenshot then shows var_dump() being used to display the data type and value of the result of isset($person->fName).

    Result Of isset($person->fName): true

    The instance of the Person class has the string “John” assigned to the property fName. The property is declared and it has a value different than Null so true is returned.

    Conclusion

    The isset() language construct is used to determine if a variable is declared and if the variable’s value is different than NULL. It is important to check if a variable is set when data is coming from outside sources such as an API, posted data from a form, or query parameters from a URL. The above examples show the results of using isset() to determine if variables are considered set by PHP.

    References:https://www.php.net/manual/en/function.isset.phphttps://www.php.net/manual/en/function.unset.phphttps://kunststube.net/issethttps://david.garden/when-to-use-isset-empty-and-is_null-in-phphttps://www.youtube.com/watch?v=Cg0S8VgOrxY

Mentions

Likes

Reposts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Your post must include a link to this post.

How does this work?
Write a response on your own website and include a link to this post. Then submit your response’s URL here. Your response may appear here after moderation. To update or remove it, edit or delete your original post and submit the same URL again. Learn more about Webmentions.
🌙 ☀️