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.

1

2

3

4

<?php

$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.

1

2

3

4

<?php

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

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

Tags

About This Blog

I'm writing this blog in order to share what I'm learning with the world. Since you learn best by teaching others and writing things down, I figured this would be the best way to really tackle any new technologies I plan on learning. I hope this blog will help you as much as it will benefit me.