The new null coalescing operator in PHP is surely a great feature, somewhat comparable to JavaScript's usage of ||
for getting default values.
I already read some documentations and articles about this feature, but some things are still not quite clear to me.
1. Can I use this operator with any number of operands? For example, would this be valid?
$a = $p1 ?? $p2;
$b = $r1 ?? $r2 ?? $r3 ?? $r4 ?? $r5;
2. What is about falsy values, which are not null?
$test = false ?? 0 ?? 'test';
- what will be $test
now? If it doesn't work with falsy values other than null, how can we achieve, that it works like JavaScript's ||
?
I created this which should answer you questions.
Anyhow
The operator can be chained and it will return the first element in the chain that is set and not null.
According to the documentation it will
return the result of its first operand if it exists and is not NULL, or else its second operand
. Hence, if the first operand isfalse
, it will returnfalse
.