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.
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
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.