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.

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.

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