Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 305
Green Joffer Avatar asked Oct 20 '20 08:10

Green Joffer


People also ask

What is the double question mark operator?

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.

What does 2 question marks mean in C#?

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"

What does double question mark mean in react?

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.

What does two question marks mean in programming?

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.


1 Answers

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.

like image 200
Green Joffer Avatar answered Sep 24 '22 10:09

Green Joffer