From the docs:
Coalesce equal or ??=operator is an assignment operator. If the left parameter is null, assigns the value of the right parameter to the left one. If the value is not null, nothing is done.
Example:
// The following lines are doing the same
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';
// Instead of repeating variables with long names, the equal coalesce operator is used
$this->request->data['comments']['user_id'] ??= 'value';
So it's basically just a shorthand to assign a value if it hasn't been assigned before.
Answer from Pavel Lint on Stack OverflowVideos
From the docs:
Coalesce equal or ??=operator is an assignment operator. If the left parameter is null, assigns the value of the right parameter to the left one. If the value is not null, nothing is done.
Example:
// The following lines are doing the same
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';
// Instead of repeating variables with long names, the equal coalesce operator is used
$this->request->data['comments']['user_id'] ??= 'value';
So it's basically just a shorthand to assign a value if it hasn't been assigned before.
Null coalescing assignment operator chaining:
$a = null;
$b = null;
a ??=
c;
print $b; // c
print $a; // c
Example at 3v4l.org
Elvis
?:returns the first argument if it contains a "true-ish" value (see which values are considered loosely equal totruein the first line of the Loose comparisons with == table). Or the second argument otherwise$result = $var ?: 'default'; // is a shorthand for $result = $var ? $var : 'default';Null coalescing
??returns the first argument if it's set and is notnull. Or the second argument otherwise$result = $var ?? 'default'; // is a shorthand for $result = isset($var) ? $var : 'default';
When your first argument is null, they're basically the same except that the null coalescing won't output an E_NOTICE when you have an undefined variable. The PHP 7.0 migration docs has this to say:
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
Here's some example code to demonstrate this:
<?php
$a = null;
print $a ?? 'b'; // b
print "\n";
print $a ?: 'b'; // b
print "\n";
print $c ?? 'a'; // a
print "\n";
print $c ?: 'a'; // Notice: Undefined variable: c in /in/apAIb on line 14
print "\n";
$b = array('a' => null);
print $b['a'] ?? 'd'; // d
print "\n";
print $b['a'] ?: 'd'; // d
print "\n";
print $b['c'] ?? 'e'; // e
print "\n";
print $b['c'] ?: 'e'; // Notice: Undefined index: c in /in/apAIb on line 33
print "\n";
The lines that have the notice are the ones where I'm using the shorthand ternary operator as opposed to the null coalescing operator. However, even with the notice, PHP will give the same response back.
Execute the code: https://3v4l.org/McavC
Of course, this is always assuming the first argument is null. Once it's no longer null, then you end up with differences in that the ?? operator would always return the first argument while the ?: shorthand would only if the first argument was truthy, and that relies on how PHP would type-cast things to a boolean.
So:
$a = false ?? 'f'; // false
$b = false ?: 'g'; // 'g'
would then have $a be equal to false and $b equal to 'g'.
Ran the below on php interactive mode (php -a on terminal). The comment on each line shows the result.
var_export (false ?? 'value2'); // false
var_export (true ?? 'value2'); // true
var_export (null ?? 'value2'); // value2
var_export ('' ?? 'value2'); // ""
var_export (0 ?? 'value2'); // 0
var_export (false ?: 'value2'); // value2
var_export (true ?: 'value2'); // true
var_export (null ?: 'value2'); // value2
var_export ('' ?: 'value2'); // value2
var_export (0 ?: 'value2'); // value2
The Null Coalescing Operator ??
??is like a "gate" that only lets NULL through.- So, it always returns first parameter, unless first parameter happens to be
NULL. - This means
??is same as( !isset() || is_null() )
Use of ??
- shorten
!isset() || is_null()check - e.g
$object = $object ?? new objClassName();
Stacking Null Coalese Operator
$v = $x ?? $y ?? $z;
// This is a sequence of "SET && NOT NULL"s:
if( $x && !is_null($x) ){
return $x;
} else if( $y && !is_null($y) ){
return $y;
} else {
return $z;
}
The Ternary Operator ?:
?:is like a gate that letsanything falsythrough - includingNULL- Anything falsy:
0,empty string,NULL,false,!isset(),empty() - Same like old ternary operator:
X ? Y : Z - Note:
?:will throwPHP NOTICEon undefined (unsetor!isset()) variables
Use of ?:
- checking
empty(),!isset(),is_null()etc - shorten ternary operation like
!empty($x) ? $x : $yto$x ?: $y - shorten
if(!$x) { echo $x; } else { echo $y; }toecho $x ?: $y
Stacking Ternary Operator
echo 0 ?: 1 ?: 2 ?: 3; //1
echo 1 ?: 0 ?: 3 ?: 2; //1
echo 2 ?: 1 ?: 0 ?: 3; //2
echo 3 ?: 2 ?: 1 ?: 0; //3
echo 0 ?: 1 ?: 2 ?: 3; //1
echo 0 ?: 0 ?: 2 ?: 3; //2
echo 0 ?: 0 ?: 0 ?: 3; //3
// Source & Credit: http://php.net/manual/en/language.operators.comparison.php#95997
// This is basically a sequence of:
if( truthy ) {}
else if(truthy ) {}
else if(truthy ) {}
..
else {}
Stacking both, we can shorten this:
if( isset($_GET['name']) && !is_null($_GET['name'])) {
$name = $_GET['name'];
} else if( !empty($user_name) ) {
$name = $user_name;
} else {
$name = 'anonymous';
}
To this:
$name = $_GET['name'] ?? $user_name ?: 'anonymous';
Cool, right? :-)
Hi,
There are really two questions - at some point in programming PHP these past 2 years I started avoiding the null coalescing operator (??), but I don’t really know why since they all use 7.2 and the docs say the operator is available starting in 7.0.
Is the null coalescing operator safe in 7.2 and up?
Will it store null if there’s an exception generated, especially indexing a nested array and trying to Index on null or undefined?
Does isset() catch exceptions and return null as well? Or will it throw an exception?
Thanks!