从可能不存在而没有错误的数组值分配 PHP 变量的最快方法

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

这是一种代码高尔夫,但我不觉得这是题外话,因为这个问题实际上在我工作时经常出现,保持代码简洁和可读性非常 on话题.

//$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

工作正常,但变量名较长等会变得很长,并且难以读取大的多维数组...

[
    'Foo' => 'Bar',
    'Boo' => [
         'FooBarMacFooBar' => ( isset($SomeOtherLongVariable['BooBarMcFooFar']) ) ? $SomeOtherLongVariable['BooBarMcFooFar'] : NULL )
     ] ; 
]

除了丑陋和难以阅读之外,它不符合 PSR-2 的最大线宽(80?)。

这样飞机就不会坠毁了...

[
    'Foo' => 'Bar',
    'Boo' => [
         // THIS WILL THROW AND ERROR NOTICE IF THE KEY DOESN'T EXIST
         'FooBarMacFooBar' => $SomeOtherLongVariable['BooBarMcFooFar']
     ] ; 
]

...但是如果数组的内容未知,它将用关于 "array key doesn't exist".

的错误通知填满日志

有解决办法吗? (除了写一个辅助函数)

(...除了使用 Ruby :-)

这已经困扰 PHP 开发人员多年,在 PHP 7 中,COALESCE 运算符 ?? 终于出现了:

新方式(从PHP 7开始):

$variable = $array['A'] ?? null

与您的代码完全相同。

引用 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

旧方法(hackish 解决方法):

$variable = @$array['A'] ?: null;

这使用错误抑制运算符 @ 来使通知静音,并使用短三元运算符 ?:。如果我们只需要设置$variablenull,如果不设置$array['A'],可以缩短为

$variable = @$array['A'];

需要注意的是,@ 被认为是不好的做法,我实际上觉得推荐它有点脏,但如果你能忍受偶尔违反最佳做法,这是一种不适合的情况危害:

这一行可能只发生一个错误(未定义 variable/offset)。你期待它并优雅地处理它。