Difference Between isset and empty in PHP
Understanding the difference between isset() and
empty() is crucial for writing clean and bug-free PHP code.
While both functions are used to check the state of variables, they
behave differently when handling null, empty strings, zeros, and
undefined variables. This article provides a clear comparison of how
isset() and empty() evaluate various values,
helping you choose the right function for your conditional checks.
What is isset()?
The isset() function determines whether a variable is
declared and is not null.
- It returns
trueif the variable exists and has any value other thannull(including0, empty strings, orfalse). - It returns
falseif the variable does not exist, or if it is explicitly set tonull.
$var = "";
var_dump(isset($var)); // Returns true
$var2 = null;
var_dump(isset($var2)); // Returns falseWhat is empty()?
The empty() function determines whether a variable is
empty. A variable is considered empty if it does not exist, or if its
value evaluates to false.
- It returns
trueif the variable is not set, or if its value is one of the following:""(an empty string)0(integer 0)0.0(float 0)"0"(string containing the character 0)nullfalse[](an empty array)
- It returns
falseif the variable exists and contains a non-empty value (like a non-zero number or a non-empty string).
$var = "";
var_dump(empty($var)); // Returns true
$var2 = "Hello";
var_dump(empty($var2)); // Returns falseComparison Table
The table below illustrates how isset() and
empty() evaluate different variable states:
| Variable Value | isset() Output | empty() Output |
|---|---|---|
| Undefined variable | false |
true |
null |
false |
true |
"" (empty string) |
true |
true |
0 (integer) |
true |
true |
"0" (string) |
true |
true |
[] (empty array) |
true |
true |
false |
true |
true |
true |
true |
false |
"hello" (string) |
true |
false |
When to Use Which?
- Use
isset()when you want to verify if a variable or an array key exists, regardless of whether its content is “falsy.” This is ideal for checking if form checkboxes were submitted or if specific optional array configuration parameters are present. - Use
empty()when you want to ensure a variable contains meaningful data before using it. This is useful for validating required text inputs from user forms, where spaces or empty strings should be treated as missing information.