How to Check If a Variable is Null in PHP

09/07/2021
Contents
In this article, you will learn how to check if a variable is null in PHP.
PHP is_null() Function
The is_null() function is a language construct that can be used to determine if a variable is equal to null. It returns true if the variable is null, and false otherwise.
Syntax:
bool is_null ( mixed $var )
Parameters:
$var
: The variable to be tested.
Example:
<?php
$variable = null;
if (is_null($variable)) {
echo "The variable is null";
} else {
echo "The variable is not null";
}
?>
This will output: The variable is null.
The comparison operator (===)
You can also check if a variable is null in PHP using the comparison operator ===:
<?php
if ($variable === null) {
// do something
}
?>
Using the comparison operator === allows you to check if a variable is equal to null, including its type, which must be exactly null.
It’s important to use the === operator or is_null function to check for null, rather than using ==, because == performs type coercion and may give unexpected results. For example, 0 == null is true, while 0 === null is false.