Home » Php » Quickest way to assign a PHP variable from an array value that may not exist without error

Quickest way to assign a PHP variable from an array value that may not exist without error

Posted by: admin July 12, 2020 Leave a comment

Questions:

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 🙂

How to&Answers:

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 not NULL, or else its second operand. This means the $_GET['mykey'] ?? "" is completely safe and will not raise an E_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.