Null coalesce operator in PHP 7

catgirl

Administrator
Staff member
Administrator
May 28, 2020
155
28
22
United States
envyforums.net
In PHP often you will set the value of a variable to equal that of another value that may or may not be set (for example GET and POST parameters), as a result you'll need to use functions such as isset() or empty() to ensure that the value exists and isn't empty. As a result this can result in a lot of branching code that reduces readability of your codebase.

Consider the following code...
PHP:
<?php
    $name = "";
    if (isset($_GET['name'])) {
        if(!empty($_GET['name'])) {
            $name = $_GET['name'];
        }
        else {
            throw new Exception('Name empty!');
        }
    } else {
        throw new Exception('Name does not exist!');
    }
?>
As seen the check can create several lines of code. Thankfully PHP 7 provides us with a better way, the null coalesce operator. It provides a shorthand for what to do or set if the value is empty.

PHP:
<?php
    $name = $_GET['name'] ?? "User";
?>
By using the null coalesce operator you can produce smaller and more readable code. What do you think about this PHP feature? Will you keep using long hand checks or switch to the null coalesce operator?