The correct answer above from @mrks can be shortened to:
$params['phone'] ??= 'default';
RFC: Null coalesce equal operator
Answer from Dmitry Bordun on Stack OverflowThe correct answer above from @mrks can be shortened to:
$params['phone'] ??= 'default';
RFC: Null coalesce equal operator
You don't add anything to params. Your given code simply generates an unused return value:
$params['phone'] ?? 'default'; // returns phone number or "default", but is unused
Thus, you will still have to set it:
$params['phone'] = $params['phone'] ?? 'default';
What is the syntax of the null coalescing operator?
$variable = $value ?? $default;
Here, $value is checked first. If it is null, $default is used instead.When should I use the null coalescing operator?
Does the null coalescing operator work with functions?
$username = getUserName() ?? 'Guest';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!