JD Lien
WebArtisan.info

WebArtisan.info

How to Clean Up Your Code with the Null Coalescing Operator (Double Question Mark Operator ??)

How to Clean Up Your Code with the Null Coalescing Operator (Double Question Mark Operator ??)

What is ?? in PHP?

JD Lien's photo
JD Lien
·Jun 1, 2022·

2 min read

Have you ever seen code with the ?? operator and wondered what it does? Was the programmer so confused that they just threw in a bunch of extra question marks?

Nope! This is called the "null coalescing" operator and was introduced in PHP 7. "Coalesce" is a fancy word meaning "put together". This is a nice way to simplify a bit of code when you need to check if a variable is defined or not null.

Let's view an example where a not-so-bright alien named Carg is going to order coffee from our web site. Our normal order page asks the user to enter what they'd like to order, but we don't want to confuse Carg with a bunch of options he isn't interested in, so we made him a separate ordering page where all he can order is coffee.

To keep things simple for us, both pages use the same "action" page to process the order. In that case, we can't be sure if the "item" post variable is set so we might need some code like this:

<?php
if (isset($_POST['item'])) {
    $item = $_POST['item'];
} else {
    $item = 'coffee';
}

echo $item;

The above code checks that the $_POST['item'] "item" submitted via a post request is set and not missing. If it is, it sets a new $item variable with the same value. If not, it sets $item to a default of 'coffee'. It then prints the value of $item.

But that does seem like an awful lot of code just to say "If the user doesn't send me anything, just assume they want coffee".

We can write this in a simpler way using the null coalescing operator.

<?php
$item = $_POST['item'] ?? 'coffee';

echo $item;

Now we have reduced the above block of code to a single, simple line. Much better!

As a bonus tip, in PHP 7.4 or greater, you can clean this up even more using the "null coalescing assignment operator". This combines ?? operator with the = (assignment operator) so that you can immediately assign a value to a variable but only if it doesn't already have a value. This is kind of like giving a variable a default in case a value wasn't already provided.

This is particularly useful if you don't want to set a new $item variable like we did in our above example, directly using the $_POST['item'] variable like so.

<?php
$_POST['item'] ??= 'coffee';

echo $_POST['item'];

Much cleaner code! Now we can get on to writing the rest of the code to handle getting Carg his coffee.

If you found this interesting follow me on Twitter for more tips like this!

 
Share this