The null coalescing operator helps you quickly choose a value that is not null. It makes your code shorter and easier to read when checking if something exists or has a value.
0
0
Null coalescing operator in PHP
Introduction
When you want to use a default value if a variable is not set or is null.
When reading user input that might be missing or empty.
When working with arrays or objects where some keys or properties might not exist.
When you want to avoid long if-else checks for null or undefined values.
Syntax
PHP
$value = $variable ?? $defaultValue;
The operator is written as two question marks: ??.
It returns the left value if it is set and not null; otherwise, it returns the right value.
Examples
If
$userName is set and not null, $name gets its value; otherwise, it becomes 'Guest'.PHP
$name = $userName ?? 'Guest';Uses 18 as a default age if
$inputAge is null or not set.PHP
$age = $inputAge ?? 18;Chooses the color from preferences if available; otherwise, defaults to 'blue'.
PHP
$color = $preferences['color'] ?? 'blue';
Sample Program
This program prints a greeting. Since $userInput is null, it prints the default message.
PHP
<?php // Example using null coalescing operator $userInput = null; $default = 'Hello, friend!'; // Use ?? to pick user input if set and not null, else default $message = $userInput ?? $default; echo $message;
OutputSuccess
Important Notes
The null coalescing operator only checks for null or unset variables, not other falsey values like 0 or empty string.
You can chain multiple ?? operators to check several values in order.
Summary
The null coalescing operator ?? returns the first value that is set and not null.
It helps simplify code that needs default values.
Use it to avoid long if-else statements when checking for null or unset variables.