Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 493
Ivo Danihelka Avatar asked Dec 14 '10 16:12

Ivo Danihelka


3 Answers

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.

like image 170
BoltClock Avatar answered Oct 12 '22 23:10

BoltClock


Actually the isset variation is the anti-pattern. If you just use isset($var)?$var:NULL with the intention to suppress the "error", then you've achieved nothing over using the proper syntax for suppressing errors. It has the same outcome, yet is less readable.

People are arguing for that because of perceived "cleanliness" and because using isset is a micro optimization. Avoiding @ and using isset as syntactic salt replacement is just cargo cult programming.

like image 45
mario Avatar answered Oct 12 '22 22:10

mario


Or

$value = (isset($array['possibly_missing_key'])) ? $array['possibly_missing_key']: null;
like image 32
Mark Baker Avatar answered Oct 13 '22 00:10

Mark Baker