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.

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.

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

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?