Null Coalescing Operator in PHP: What It Is and How to Use
null coalescing operator (??) in PHP returns the first operand if it exists and is not null; otherwise, it returns the second operand. It is a shorthand way to provide default values when dealing with variables that might be undefined or null.How It Works
The null coalescing operator ?? checks if a value exists and is not null. Think of it like asking: "Is this value set and meaningful?" If yes, use it; if not, use a backup value instead.
Imagine you have a box that might be empty or missing. Instead of opening it and checking carefully, you just say, "If the box has something, take it; otherwise, take this other box." This operator does exactly that in code, making it easier to handle missing or empty data without extra checks.
Example
This example shows how to use the null coalescing operator to provide a default value when a variable is not set or is null.
<?php $username = $_GET['user'] ?? 'guest'; echo "Hello, $username!"; ?>
When to Use
Use the null coalescing operator when you want to safely access variables that might not be set or could be null, such as user input, configuration values, or array keys. It helps avoid errors and makes your code cleaner by replacing longer isset() checks.
For example, when reading query parameters from a URL or fetching optional settings, this operator lets you provide a fallback value easily.
Key Points
- The operator is written as
??. - It returns the left value if it exists and is not
null. - If the left value is missing or
null, it returns the right value. - It is a shorthand for common
isset()checks. - Introduced in PHP 7.0 for cleaner, safer code.