PHP is_null() Function
PHP is_null() checks whether a variable is NULL. It returns true only when the value is exactly NULL.
NULL is a special value in PHP that means “no value”. A variable becomes NULL when you assign NULL to it, or when a function has nothing to return.
Syntax
is_null(mixed $value): bool
Parameters
| Parameter | Description |
|---|---|
| value | Required. The variable or value you want to test |
Return value: true if the value is NULL, otherwise false.
Examples
Example #1: NULL, 0 and empty string
Only NULL gives true. Values like 0 and empty string are not NULL.
<?php
$a = null;
$b = 0;
$c = "";
var_dump(is_null($a));
var_dump(is_null($b));
var_dump(is_null($c));
?>
Output:
Tutorials Class - Output Window
bool(true)
bool(false)
bool(false)
Example #2: Use in if else
<?php
$result = null;
if (is_null($result)) {
echo "Variable is NULL";
} else {
echo "Variable is not NULL";
}
?>
Output:
Tutorials Class - Output Window
Variable is NULL
Example #3: Function returns NULL
Many functions return NULL when they do not find anything. Here our own function returns NULL if the user id is not 1.
<?php
function findUser($id) {
return $id == 1 ? "Robin" : null;
}
$user = findUser(2);
if (is_null($user)) {
echo "User not found";
} else {
echo "Hello, " . $user;
}
?>
Output:
Tutorials Class - Output Window
User not found
Example #4: is_null() and === null
Both ways give same result. Using === null is a bit shorter, so some developers prefer it.
<?php
$a = null;
var_dump(is_null($a));
var_dump($a === null);
?>
Output:
Tutorials Class - Output Window
bool(true)
bool(true)
is_null() vs isset() vs empty()
| Value | is_null() | isset() | empty() |
|---|---|---|---|
| NULL | true | false | true |
| 0 | false | true | true |
| “” (empty string) | false | true | true |
| “Hello” | false | true | false |
| Undefined variable | true (with warning) | false | true |
Note:
If you pass an undefined variable to is_null(), PHP gives a warning “Undefined variable”. Use isset() when you are not sure that the variable exists.
Summary
- is_null() returns true only for the NULL value.
- 0, “” and false are not NULL.
- It gives a warning for undefined variable, isset() does not.
$var === nullworks same as is_null($var).
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |