PHP Null Coalescing
What is Null Coalescing?
Section titled “What is 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';Basic Usage
Section titled “Basic Usage”Simple Default Values
Section titled “Simple Default Values”$username = null;$user = $username ?? 'guest';echo $user; // "guest"With Form Data
Section titled “With Form Data”$name = $_POST['name'] ?? 'Anonymous';$email = $_GET['email'] ?? '';$age = $_POST['age'] ?? 0;Chaining
Section titled “Chaining”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';With Arrays
Section titled “With Arrays”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; // falseAssignment Operator (??=)
Section titled “Assignment Operator (??=)”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'Practical Examples
Section titled “Practical Examples”Configuration with Fallbacks
Section titled “Configuration with Fallbacks”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');Handling API Responses
Section titled “Handling API Responses”$response = [ 'user' => [ 'name' => 'Alice', 'email' => 'alice@example.com' ]];
$name = $response['user']['name'] ?? 'Unknown';$phone = $response['user']['phone'] ?? 'Not provided';Comparison with Other Operators
Section titled “Comparison with Other Operators”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 defaultecho $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 defaultecho $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.