Search code examples
operator-keywordphp-7.4

(??=) Double question mark and an equal sign, what does that operator do?


Once I stumbled with php7 code with operator ??=. I tried to search, what it clearly does, but could not find easily. I tried to read out the php operators and even most official resources have all operators description and even compound operators like .=, +=, but there are no description for ??=

For example, PHP Operators keeps descriptions of all operators, as straight form (., +), as compound (.=, +=), but there is no ??=, and because of that I firstly was confused and thought it's something totally another. The issue is simple and obvious, but the whole case is a bit confusing, that's why I try to help other php-beginners like me


Solution

  • So eventually I decided to write code and watch by myself - how it works and what it does.

    In PHP7.0 was added the Null Coalescing operator:

    $username = $_GET['username'] ?? 'not passed'; 
    

    Our $username will have $_GET['username'] value - if it exists and not null, otherwise $username will get 'not passed' string. But sometimes you can have a situation, when you need to check for existence and not-nullability the variable itself:

    $first_test = $first_test ?? 'not started';
    

    And in this situation you can use a compound version of null coalescing operator - '??=':

    $first_test ??= 'not started';
    

    That's it, just compound version of '??' for the cases, where you check the itself variable.