Skip to content

PHP Null Coalescing

The null coalescing operator (??) provides a clean way to assign default values when a variable might be null or undefined. It returns the left operand if it exists and is not null, otherwise it returns the right operand.

$result = $variable ?? 'default';
// Equivalent to:
$result = isset($variable) ? $variable : 'default';

$username = null;
$user = $username ?? 'guest';
echo $user; // "guest"
$name = $_POST['name'] ?? 'Anonymous';
$email = $_GET['email'] ?? '';
$age = $_POST['age'] ?? 0;

You can chain multiple ?? operators. PHP evaluates left to right and returns the first non-null value.

$theme = $_GET['theme'] ?? $_COOKIE['theme'] ?? $_SESSION['theme'] ?? 'light';
$dbHost = $_ENV['DB_HOST'] ?? $_SERVER['DB_HOST'] ?? 'localhost';

Null coalescing is useful for accessing array keys that might not exist:

$config = ['database' => 'mysql', 'port' => 3306];
$host = $config['host'] ?? 'localhost'; // 'localhost'
$timeout = $config['timeout'] ?? 30; // 30
$ssl = $config['ssl'] ?? false; // false

The ??= operator (PHP 7.4+) assigns a value only if the variable is null or undefined:

$settings = [];
$settings['language'] ??= 'en';
$settings['timezone'] ??= 'UTC';
// If already set, value won't change
$settings['language'] = 'fr';
$settings['language'] ??= 'en';
echo $settings['language']; // Still 'fr'

class Config {
private $settings = [];
public function get($key, $default = null) {
return $this->settings[$key] ?? $default;
}
}
$config = new Config();
$apiUrl = $config->get('api_url', 'https://api.example.com');
$response = [
'user' => [
'name' => 'Alice',
'email' => 'alice@example.com'
]
];
$name = $response['user']['name'] ?? 'Unknown';
$phone = $response['user']['phone'] ?? 'Not provided';

The key difference: ?? only checks for null/undefined, while || checks for all falsy values.

$empty = '';
$zero = 0;
$null = null;
// Null coalescing (??) - only null/undefined triggers default
echo $empty ?? 'default'; // '' (empty string is not null)
echo $zero ?? 'default'; // 0 (zero is not null)
echo $null ?? 'default'; // 'default'
// Logical OR (||) - any falsy value triggers default
echo $empty || 'default'; // 'default' (empty string is falsy)
echo $zero || 'default'; // 'default' (zero is falsy)
echo $null || 'default'; // 'default'

Use ?? when you want to allow empty strings, zero, or false as valid values. Use || when you want to replace any falsy value.