Test for null with === null. isset() is true only when something exists and is not null, so use array_key_exists() when a stored null matters. A declared type rejects null unless you allow it with ?string (PHP 7.1), short for string|null. ?? (7.0) returns its left side unless that is null or undefined, without a warning; ??= (7.4) assigns only in that case; and ?-> (8.0) stops a chain at the first null.
<?php
declare(strict_types=1);
function greet(?string $name): string // ?string is short for string|null
{
return 'Hello, ' . ($name ?? 'guest');
}
$opts = ['currency' => 'USD', 'timezone' => null];
$opts['locale'] ??= 'en_US'; // assigns only when missing or null
$shipped = null; // a ?DateTimeImmutable not set yet
echo greet(null), ' | ', $opts['timezone'] ?? 'UTC', ' | ', $opts['locale'], "\n";
echo $shipped?->format('Y-m-d') ?? 'not shipped', "\n";
var_dump(isset($opts['timezone']), array_key_exists('timezone', $opts));Output
Hello, guest | UTC | en_US not shipped bool(false) bool(true)