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 OverflowHas there been any talk of an "empty" coalesce operator?
php 7.1 - Php Null coalescing operator - Stack Overflow
Does PHP 7.2 and up support null coalescing operators that nullify exceptions?
Here's a quick tip: you can use the null coalescing assignment operator for easy memoisation in PHP 7.4
Videos
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
I'm a big fan of null coalesce, but I want more. There are definitely times where I want to set a default value if a variable is "empty". Perl has two coalesce operators:
$num ||= 8; # Empty coalesce $num //= 8; # null/undef coalesce
Any chance PHP will get any sort of empty coalesce operator? Right now I'm writing out:
if (empty($num)) { $num = 8; }which is a lot more typing, not chainable, and less readable? It'd be really nice to be able to do something like:
$num = $cost ||| $prev_num ||| $default_val;
Where ||| is the operator I made up for empty coalesce.
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!