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
In PHP 7, the double question mark(??) operator known as Null Coalescing Operator. It returns its first operand if it exists and is not NULL; otherwise, it returns its second operand. It evaluates from left to right.
The C# double question mark operator ?? is called the null-coalescing operator. It is used to return the left hand side operand of the operator if the value is not null and the right hand side operand if the value is null. For example. string value = null; string text = value ?? "The value is null"
Double question marks(??) or nullish coalescing operator helps us to assign default values to null or undefined variables in Angular and Typescript. It's often called as Null coalescing operator.
In simplest way, two question marks are called "Coalescing Operator", which returns first non null value from the chain. e.g if you are getting a values from a nullable object, in a variable which is not nullable, then you can use this operator.
So eventually I decided to wright 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With