Null coalescing operator also usable with falsy values, but not nulls?

196 views Asked by At

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 ||?

1

There are 1 answers

0
marcosh On BEST ANSWER

I created this which should answer you questions.

Anyhow

  1. The operator can be chained and it will return the first element in the chain that is set and not null.

  2. 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 is false, it will return false.