Difference Between isset and is_null in PHP
When programming in PHP, checking the state and value of variables is
a fundamental task. This article explains the distinct differences
between isset() and is_null(), detailing how
they handle defined, undefined, and null variables, and provides clear
guidance on when to use each function in your code.
What is isset()?
The isset() function is a PHP language construct used to
determine if a variable is declared and is not null.
- Returns
trueif the variable exists and has a value other thannull. - Returns
falseif the variable isnullor if the variable has not been defined yet.
A key benefit of isset() is that it does not generate
any warning or notice if you pass an undefined variable to it.
$existingVar = "Hello";
$nullVar = null;
var_dump(isset($existingVar)); // true
var_dump(isset($nullVar)); // false
var_dump(isset($undefinedVar)); // false (no warning triggered)What is is_null()?
The is_null() function is a standard PHP function used
to check if a variable is specifically set to null.
- Returns
trueif the variable value isnull. - Returns
falseif the variable has any other value (even empty strings,0, orfalse).
Unlike isset(), if you pass an undefined variable to
is_null(), PHP will trigger an “Undefined variable”
warning.
$nullVar = null;
$emptyStr = "";
var_dump(is_null($nullVar)); // true
var_dump(is_null($emptyStr)); // false
var_dump(is_null($undefinedVar)); // true (triggers an Undefined Variable warning)Key Differences
1. Handling Undefined Variables
The most critical difference is how they handle variables that do not
exist. isset() safely returns false without
raising an error. is_null() expects the variable to exist;
if it does not, PHP throws a warning.
2. Language Construct vs. Function
isset() is a language construct, not a regular function.
This means it is generally faster because it has less overhead.
is_null() is a standard built-in function, which makes it
slightly slower, though the performance difference is negligible in most
applications.
3. Logic Comparison
isset($var)behaves similarly to!is_null($var)(provided$varis defined).is_null($var)behaves identically to the strict comparison$var === null.
Comparison Table
| Variable State | isset(\(var) | is_null(\)var) | |
|---|---|---|
| Undefined | false (safe) |
true (triggers warning) |
null |
false |
true |
"" (Empty
string) |
true |
false |
0
(Integer) |
true |
false |
false
(Boolean) |
true |
false |
[] (Empty
array) |
true |
false |
When to Use Which?
- Use
isset()when you want to check if a variable exists and is not null. It is ideal for checking array keys, form inputs ($_POSTor$_GET), and configuration variables that might not be declared yet. - Use
is_null()(or the strict comparison$var === null) when you are certain the variable is defined, and you specifically need to verify if its value is explicitly set tonull.