Search code examples
phparraysoperatorserror-suppression

Is @$array['possibly_missing_key'] an anti-pattern?


Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

$value = @$array['possibly_missing_key'];

The intended behavior:

if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}

I want to know, before spreading the usage pattern.


Solution

  • The @ operator suppresses error messages, and using it potentially sets up your code for other errors and unexpected behavior that end up hard to track down. Thus it's most certainly an antipattern.

    Thus, I would very much prefer the second bit. It makes it much clearer

    • that it may not be present in the array, and
    • what the default value is if it's not present

    To make it more concise you can use the ternary conditional operator ?:, as seen in Mark Baker's answer. Slightly less code and more symbols but the meaning is well-recognized.