isset()
and empty()
Functions
The isset()
and empty()
functions are both used to check the state of a variable.
Although they may seem similar, their behavior and purposes differ, so it's important to use each appropriately.
- The
isset()
function checks whether a variable exists and is notnull
. - The
empty()
function checks whether a variable is empty.
In this article, we will clarify the concepts of the isset()
and empty()
functions, explore how to use them, and highlight their key differences.
isset()
Function
Checks whether a variable exists and is not null
.
This function returns true
if the variable has been declared and its value is not null
.
Even if the value is empty (such as an empty string), as long as the variable exists, isset()
returns true
. If the variable has not been declared or its value is null
, it returns false
.
$var1 = '';
$var2 = null;
var_dump(isset($var1)); // true
var_dump(isset($var2)); // false
empty()
Function
Checks whether a variable is empty.
This function returns true
if the variable has been declared and its value is considered empty.
Empty values include 0
, ''
, null
, false
, array()
, and similar values.
However, an empty object is not considered empty. If an object exists, empty()
will return false
.
$var1 = '';
$var2 = null;
$obj = new stdClass();
var_dump(empty($var1)); // true
var_dump(empty($var2)); // true
var_dump(empty($obj)); // // false (an empty object is not considered empty)
Comparison of Differences
Here is a table that compares the differences between the isset()
and empty()
functions based on their return values.
Condition | isset() |
empty() |
---|---|---|
Variable is not declared | false |
true |
Variable has a non-empty value | true |
false |
Variable value is null |
false |
true |
Variable is an empty string ('' ) |
true |
true |
Variable is 0 |
true |
true |
Variable is an empty array | true |
true |
Variable is an empty object | true |
false |
Flexible Error Handling
Comparing the isset()
and empty()
functions is especially important for error prevention.
They provide a way to avoid warning messages that occur when accessing undefined or improperly declared variables.
For example, using isset()
to check an undeclared variable will work without triggering an error. However, empty()
requires the variable to be declared in order to work properly.
Therefore:
- Use
isset()
when you need to check whether a variable exists. - Use
empty()
when you want to check whether a variable is considered empty.