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

Is @$array['possibly_missing_key'] an anti-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

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


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.


Or

$value = (isset($array['possibly_missing_key'])) ? $array['possibly_missing_key']: null;