Quickest way to assign a PHP variable from an array value that may not exist without error
This has been bothering PHP developers for years and in PHP 7 the COALESCE operator ??
finally arrived:
The new way (starting with PHP 7):
$variable = $array['A'] ?? null
does exactly the same as your code.
Quoting the RFC:
The coalesce, or
??
, operator is added, which returns the result of its first operand if it exists and is notNULL
, or else its second operand. This means the$_GET['mykey'] ?? ""
is completely safe and will not raise anE_NOTICE
The old way (hackish workaround):
$variable = @$array['A'] ?: null;
This uses the error suppression operator @
to silence the notice, and the short ternary operator ?:
. If we only need to set $variable
to null
if $array['A']
is not set, it can be shortened to
$variable = @$array['A'];
It should be noted that @
is considered bad practice and I actually feel a bit dirty recommending it, but if you can live with the occasional best practice violation, this is a situation where it does not do harm:
There is only one possible error that can happen in this line (undefined variable/offset). You expect it and handle it gracefully.