Frank Perez

Frank Perez

Keep in touch

An experienced Web Developer with years of experience in design, programming and server administration.



© 2024 by Frank Perez.

PHP Null Coalescing Operator

One of my new favorite additions to PHP 7, is the Null Coalesce Operator. It cleans up your code by removing a tedious step of checking if some value is isset() and not NULL and returning it or if not setting a default.

I think the best way to show you this example, is maybe to show you how you may have written something before this feature was released and how you can clean it up now that the Null Coalescing Operator exists.

Old Way

So let’s look at how you may have handled checking of some data exists from a $_GET request.


$sort = isset($_GET['sort']) ? $_GET['sort'] : 'ASC';

This is honestly a bit tedious to do each time you need some type of value set by default for any variable.

New, Better Way

Now, let’s go over how you can clean up the old code with our new available null coalescing operator.


$sort = $_GET['sort'] ?? 'ASC';

This is now much cleaner and removes some of the repetition you were typing before.