What does double question mark (??) operator mean in PHP
Solution 1
It's the "null coalescing operator", added in php 7.0. The definition of how it works is:
It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
So it's actually just isset()
in a handy operator.
Those two are equivalent1:
$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';
Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce
In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
And original RFC https://wiki.php.net/rfc/isset_ternary
EDIT: As this answer gets a lot of views, little clarification:
1There is a difference: In case of ??
, the first expression is evaluated only once, as opposed to ? :
, where the expression is first evaluated in the condition section, then the second time in the "answer" section.
Solution 2
$myVar = $someVar ?? 42;
Is equivalent to :
$myVar = isset($someVar) ? $someVar : 42;
For constants, the behaviour is the same when using a constant that already exists :
define("FOO", "bar");
define("BAR", null);
$MyVar = FOO ?? "42";
$MyVar2 = BAR ?? "42";
echo $MyVar . PHP_EOL; // bar
echo $MyVar2 . PHP_EOL; // 42
However, for constants that don't exist, this is different :
$MyVar3 = IDONTEXIST ?? "42"; // Raises a warning
echo $MyVar3 . PHP_EOL; // IDONTEXIST
Warning: Use of undefined constant IDONTEXIST - assumed 'IDONTEXIST' (this will throw an Error in a future version of PHP)
Php will convert the non-existing constant to a string.
You can use constant("ConstantName")
that returns the value of the constant or null if the constant doesn't exist, but it will still raise a warning. You can prepended the function with the error control operator @
to ignore the warning message :
$myVar = @constant("IDONTEXIST") ?? "42"; // No warning displayed anymore
echo $myVar . PHP_EOL; // 42
Solution 3
$x = $y ?? 'dev'
is short hand for x = y if y is set, otherwise x = 'dev'
There is also
$x = $y =="SOMETHING" ? 10 : 20
meaning if y equals 'SOMETHING' then x = 10, otherwise x = 20
elkolotfi
Computer engineer for more 6 years now. Kinda Wayne Rooney of programming: I speak PHP, Java, Cobol... Solving problems is a hobby to me
Updated on September 09, 2021Comments
-
elkolotfi over 2 years
I was diving into Symfony framework (version 4) code and found this piece of code:
$env = $_SERVER['APP_ENV'] ?? 'dev';
I'm not sure what this actually does but I imagine that it expands to something like:
$env = $_SERVER['APP_ENV'] != null ? $_SERVER['APP_ENV'] : 'dev';
Or maybe:
$env = isset($_SERVER['APP_ENV']) ? $_SERVER['APP_ENV'] : 'dev';
Does someone have any precision about the subject?
-
ascsoftw over 4 years$foo = isset($y++) ? $y++ : 'something'; This doesn't work. Can not use isset on the result of an expression.
-
michalhosna over 4 years@ascsoftw sorry, removed until i find of better example
-
Tomek over 4 yearsRegarding the last edit : the number of times it gets evaluated also depends on the internal implementation of the ?? operator (is it really once?)
-
ksadowski about 4 years+1 for the documentation link. I end up here every now and then because the operator has to be spelled out for Google to treat it as a search term, but all I really want is to read the docs ;)
-
Valentin about 4 yearsLast edit is not very clear/concise. I had hard time reading and understanding it. Found this which clears what you wanted to say there. So please add an example. php.net/manual/en/language.operators.logical.php#115208 $a = (fruit(1) ? fruit(1) : 'apple');//fruit() will be called twice!
-
Michiel Bakker over 3 yearsNote that, like with
isset()
, this also works onundefined
(e.g. typed class properties that have not been inialized yet). -
Semra almost 3 yearsThe edit is really unnecessary and confusing. The syntax for
a??b
,a?:b
, anda?a:b
all clear enough that only the last one has duplicate evaluation -
AaA over 2 yearsso does
$value = $value ?? null;
means something? (A line from google cloud api source code) -
michalhosna over 2 years@AaA I covers the case where the variable
$value
did not exist at all. -
Kamil Dąbrowski over 2 yearsif(($_SESSION['captchaReq']++??$_SESSION['captchaReq']=0)<3) { }
-
Cid over 2 years@KamilDąbrowski yes? What's this?
-
Cid over 2 yearsIf you can't, don't bother with shortening code. A code you can read and maintain easily is way better than something short
-
Kamil Dąbrowski over 2 years$_SESSION['req']++??$_SESSION['req']=0 is easy to read take advantage of new technologies
-
Cid over 2 yearswell, you can't do
null++
, so doing$_SESSION['req']++??
makes no sense -
Kamil Dąbrowski over 2 yearsyou don't understand code is not null is 0 as begin initial any variable read again this ---> $_SESSION['req']++??$_SESSION['req']=0 You can image a lot think todo with the construction of logick avaiable from php 7> $hitCache++??$hitCache=0; it is post
-
Cid over 2 yearsWhat the point of using a null coalescing operator on something that can't be
null
?