How to Double Question Mark in PHP
PHP, one of the most popular server-side scripting languages, offers a rich set of operators and constructs that make it a versatile choice for web development. Among these, the double question mark (??
) operator is a relatively new addition introduced in PHP 7.0.
This operator, also known as the null coalescing operator, is a powerful tool for simplifying code and handling null values effectively. In this article, we’ll explore the various uses of the double question mark operator in PHP and how it can improve your code.
Use Double Question Mark as a Null Coalescing Operator in PHP
The Null Coalescing Operator (??
) is a binary operator that allows you to simplify the process of handling null values. It provides a way to choose a default value when a given expression evaluates to null.
This is particularly useful when working with variables that may or may not have values.
The basic syntax of the null coalescing operator is as follows:
$result = $value ?? $default;
In this syntax:
$value
: The variable or expression you want to check for null.$default
: The value that will be used if$value
is null.
One of the most common uses of the double question mark operator is for setting default values for variables. This is especially useful when you’re working with user input or configuration settings.
For example:
<?php
$userName = $_GET['username'] ?? 'Guest';
echo "Hello, $userName!";
?>
If you visit the page with a URL like http://example.com/index.php?username=John
, you’ll see:
Hello, John!
But if you visit the page without the username
parameter, you’ll see:
Hello, Guest!
Avoid Undefined Variable Errors
Before the null coalescing operator, you’d often need to use the isset()
function or a verbose ternary conditional to avoid Undefined variable
errors. With ??
, this is simplified:
<?php
$config = ['setting' => 'value'];
$option = $config['option'] ?? 'default';
echo "Option: $option";
?>
This code sets the $option
variable to default
because option
does not exist in the $config
array. The output will be:
Option: default
Chain the Double Question Mark Operator
You can chain multiple null coalescing operators to provide fallback values in a cascading manner. This is particularly useful for checking several variables or array keys until you find a non-null value.
<?php
$first = null;
$second = 'Hello';
$third = 'World';
$result = $first ?? $second ?? $third ?? 'default';
echo $result;
?>
The code checks $first
, which is null, then $second
, which is Hello
, and assigns the value Hello
to $result
. The output will be:
Hello
Work With Object Properties
The double question mark operator can also be used with object properties. It’s a great way to access object properties that might not exist without triggering fatal errors.
<?php
class User {
public $name = 'John';
public $address = null;
}
$user = new User();
$address = $user->address->city ?? 'Unknown';
echo "City: $address";
?>
The code sets $address
to 'Unknown'
because the address
property is set to null
, and attempting to access city
on a null value triggers the null coalescing operator. The output will be:
City: Unknown
Combine With the Ternary Operator
You can combine the null coalescing operator with the ternary conditional operator to create more complex fallback logic.
<?php
class User {
public function getCountry() {
return null;
}
}
$user = new User();
$defaultCountry = 'USA';
$country = $user->getCountry() ?? $defaultCountry ?: 'Unknown';
echo "Country: $country";
?>
The code attempts to get the country from the getCountry()
method, but it returns null
. The null coalescing operator then checks $defaultCountry
, which is USA
.
The output will be:
Country: USA
Conclusion
The double question mark operator (??
) is a valuable addition to PHP, simplifying the process of handling null values and reducing the need for lengthy conditional statements and error-prone checks. By leveraging this operator, you can write more concise and readable code while effectively handling null values and providing fallbacks where needed.
Whether you’re working with arrays, objects, user input, or configurations, the null coalescing operator is a versatile tool that should be a part of every PHP developer’s toolkit.
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn Facebook