PHP double question marks (Null coalescing operator) explained

Updated Nov 15, 2022 ⤳ 2 min read
Several paper question marks on a cardboard.
Photo by Leeloo Thefirst on Pexels

PHP double question marks (??) – officially known as Null coalescing operator – is a convenient alternative to ternary expressions in conjunction with isset().

You might have seen the following expression in your Laravel or PHP projects:


$result = $value ?? $alternativeValue;

But what do two question marks mean in PHP?

The above expression returns its first operand ($value) if it exists and is not null; otherwise, it returns the second operand ($alternativeValue).

The above expression is equivalent to:


$result = isset($value) ? $value : $alternativeValue;

How to use PHP double question marks

Before the Null coalescing operator, you'd have to use a ternary operator with a call to isset():


$iceCreamFlavor = isset($_POST['flavor']) ? $_POST['flavor'] : 'vanilla';

Or as an if statement:


$iceCreamFlavor = 'vanilla';

if (isset($_POST['flavor'])) {
  $iceCreamFlavor = $_POST['flavor'];

But with the Null coalescing operator, you can summarize it into:


$iceCreamFlavor =$_POST['flavor'] ?? 'vanilla';

You can also chain multiple operators:


$display_name =  $first_name ?? $last_name ?? 'Anonymous';

The above code will return the first defined value among $first_name, $last_name, and Anonymous.

The Null coalescing operator has been added to PHP since version 7.

I hope this quick guide gave you the answer you were looking for.

Thanks for reading!

Author photo

Hey 👋 I'm a software engineer, an author, and an open-source contributor. I enjoy helping people (including myself) decode the complex side of technology. I share my findings on Twitter: @rlavarian

If you read this far, you can tweet to the author to show them you care. Tweet a Thanks

Disclaimer: This post may contain affiliate links. I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.