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

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

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

Intended Behavior:

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

I want to know before distributing the usage pattern.

+7
source share
6 answers

The @ operator suppresses error messages, and using it potentially sets up your code for other errors and unexpected behavior that are ultimately difficult to track. Thus, it is certainly antipattern.

So I would really prefer the second bit. It makes it more understandable.

  • so that it is not present in the array, and
  • what is the default if not present

To make it more concise, you can use the ternary conditional operator ?: As shown in Mark Baker's answer . A little less code and more characters, but the meaning is well known.

+8
source

In fact, the isset option is an anti-pattern. If you just use isset($var)?$var:NULL with the intention of suppressing the "error", then you have not achieved anything using the correct syntax to suppress errors. It has the same result, but is less readable.

People claim that because of the perceived "purity" and because the use of isset is micro-optimization. Avoiding @ and using isset as a replacement for syntactic salt is just cult planning.

+6
source

or

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

Ignoring warnings is definitely an antipattern; so yes, this is an anti-pattern (and I can guarantee that if you learn to suppress warnings, one of them will come back and bite you in the back, if not worse).

In addition, while the second version is more verbose, it gives the uninitialized variable a known state (or can be used to handle the problem if the variable needs to be populated).

+1
source

The third option:

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

I know that this does not directly answer the question; I would put it as a comment, except that it really needed to be formatted.

The idea here is that if you are trying to make your code shorter using a single-line block instead of an if-else block, you can still get it in a concise single-line line using the ternary operator, you are the best of both worlds.

+1
source

The second block of code (or an alternative to Mark Baker, which will work in exactly the same way) is better. I'm not quite sure about PHP, but in many other programming languages ​​just ignoring a variable will almost certainly throw an error. At least with the second block, you initialize the variable to some value or memory location.

Error suppression should be used more often if you expect the function to output the expected error in the final product (however, most of the time this will not be the case).

Good luck
Dennis M.

+1
source

All Articles