null, isset, and ??

suggest change

In 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:

$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:

  1. isset($var) returns true only if the variable is defined AND its value is not null. It suppresses undefined variable/index warnings:
    $config = ['timeout' => 30];
    
    if (isset($config['retries'])) {
        // Won't trigger E_WARNING: Undefined array key "retries"
    }
    
  2. empty($var) returns true if the variable does not exist, or if its value evaluates to falsy (null, 0, "", "0", [], false).
  3. is_null($var) triggers an Undefined variable notice/warning if $var was 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents