null, isset, and ??
suggest changeIn PHP, managing missing values, uninitialized variables, and nullable types is a core part of day-to-day programming. PHP provides several language constructs and operators to inspect and handle null values cleanly: null, isset(), is_null(), the null coalescing operator (??), the null coalescing assignment operator (??=), and the nullsafe operator (?->).
The null Value
null represents a variable with no value. In PHP, a variable is considered null if:
- It has been explicitly assigned the constant
null. - It has not been set to any value yet.
- It has been unset using
unset().
$val = null;
var_dump(is_null($val)); // bool(true)
var_dump($val === null); // bool(true)
isset() vs. is_null() vs. empty()
Understanding how these three functions handle undefined variables, null, and falsy values is critical in PHP:
| Expression | $var is undefined |
$var = null |
$var = 0 or "" or [] |
$var = "hello" |
|---|---|---|---|---|
isset($var) |
false (no warning) |
false |
true |
true |
is_null($var) |
true (Warning/Notice) |
true |
false |
false |
empty($var) |
true (no warning) |
true |
true |
false |
$var === null |
Warning/Notice | true |
false |
false |
Key Differences:
isset($var)returnstrueonly if the variable is defined AND its value is notnull. It suppresses undefined variable/index warnings:$config = ['timeout' => 30]; if (isset($config['retries'])) { // Won't trigger E_WARNING: Undefined array key "retries" }empty($var)returnstrueif the variable does not exist, or if its value evaluates to falsy (null,0,"","0",[],false).is_null($var)triggers anUndefined variablenotice/warning if$varwas never declared.
The Null Coalescing Operator (??)
Introduced in PHP 7.0, the null coalescing operator ?? returns its first operand if it exists and is not null; otherwise, it returns its second operand.
It is equivalent to isset($a) ? $a : $b, but much more concise:
// Reading query parameter with a fallback default
$page = $_GET['page'] ?? 1;
// Nested array access without throwing "Undefined array key" warnings
$payload = [
'user' => [
'profile' => [
'theme' => 'dark'
]
]
];
$theme = $payload['user']['profile']['theme'] ?? 'light'; // "dark"
$font = $payload['user']['profile']['font'] ?? 'sans-serif'; // "sans-serif"
Chaining ??
Multiple coalescing expressions can be chained from left to right:
$displayName = $user['nickname'] ?? $user['full_name'] ?? $user['username'] ?? 'Anonymous';
Null Coalescing Assignment (??=)
Added in PHP 7.4, ??= assigns a value to a variable only if the variable is either not set or is null:
$settings = [];
// If 'timeout' is null or missing, initialize it to 60:
$settings['timeout'] ??= 60;
echo $settings['timeout']; // 60
// Existing non-null values remain untouched:
$settings['timeout'] ??= 120;
echo $settings['timeout']; // 60
The Nullsafe Operator (?->)
Added in PHP 8.0, the nullsafe operator short-circuits method or property access if the target evaluates to null:
class Address {
public function getCity(): string {
return "San Francisco";
}
}
class User {
public ?Address $address = null;
}
$user = new User();
// Without nullsafe operator:
$city = null;
if ($user->address !== null) {
$city = $user->address->getCity();
}
// With nullsafe operator:
$city = $user->address?->getCity(); // returns null without throwing an Error
Best Practices
- Use
??to provide fallback values for optional configuration and input parameters. - Use
isset()when checking whether a dictionary key or property exists without needing a default fallback. - Avoid using
empty()on variables where'0'or0are valid inputs (such as counters, quantities, or scores). - Prefer strict comparison
=== nullover loose comparison== nullto avoid treating0,"", orfalseasnull.