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.

$var = "";
var_dump(isset($var)); // Returns true

$var2 = null;
var_dump(isset($var2)); // Returns false

What 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.

$var = "";
var_dump(empty($var)); // Returns true

$var2 = "Hello";
var_dump(empty($var2)); // Returns false

Comparison 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?