This is kind of code golf but I don't feel it's off topic because the issue actually comes up often while I'm working, and keeping code concise and readable is very on topic.
//$array = ['A' => 'FOO', 'B' => 'BAR'];
//We don't necessarily know what this is
// :-)
$variable = ( isset($array['A']) ) ? $array['A'] : NULL );
//We just want $variable to be NULL if the key isn't in the array
The works fine but it gets very long with longer variable names etc, and it makes it hard to read big multi-dimensional arrays...
[
'Foo' => 'Bar',
'Boo' => [
'FooBarMacFooBar' => ( isset($SomeOtherLongVariable['BooBarMcFooFar']) ) ? $SomeOtherLongVariable['BooBarMcFooFar'] : NULL )
] ;
]
Aside from being ugly and hard to read, it's not compliant with the line width maximum (80?) of PSR-2.
The plane won't crash if I do this...
[
'Foo' => 'Bar',
'Boo' => [
// THIS WILL THROW AND ERROR NOTICE IF THE KEY DOESN'T EXIST
'FooBarMacFooBar' => $SomeOtherLongVariable['BooBarMcFooFar']
] ;
]
...but if the contents of the array is unknown, it will fill up the logs with error notices about "array key doesn't exist".
Is there a solution to this? (besides writing a helper function)
(...and besides using Ruby :-)
This has been bothering PHP developers for years and in PHP 7 the COALESCE operator ??
finally arrived:
$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
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With