Is '@' Error Suppression a Valid Technique for Testing for an Optional Array Key?

Posted by MikeSchinkel on Programmers See other posts from Programmers or by MikeSchinkel
Published on 2011-11-17T22:37:44Z Indexed on 2011/11/18 2:02 UTC
Read the original article Hit count: 341

Rarst and I were debating offline about the use of the '@' error suppression operator in PHP, specifically for use to test for existence of "optional" array keys, i.e. array keys that are being used as a switch here a their lack of existence in the array is functionally equivalent to the array having the key with a value equaling false.

Here is pseudo-code for this scenario:

 function do_something( $args = array() ) {
   if ( @$args['switch'] ) {
      // Do something with this switch
   }
   // continue on...
 }

vs. this approach:

 function do_something( $args = array() ) {
   if ( ! empty( $args['switch'] ) && $args['switch'] ) {
      // Do something with this switch
   }
   // continue on...
 }

Of course in most use-cases, suppressing errors would not be A Good Thing(tm). However in this use-case where an array is passed with an optional element, it seems to me that it is actually a very good technique but I could be wrong and would like to hear other's opinions on the subject before I make up my mind.

I do know that there are alleged performance hits for using the former approach but I'd like to know how they compare with the alternative and if they performance hits really matter in real world scenarios?

P.S. I decided to post this because, after debating this offline with Rarst, he asked a more general question here on Programmers but didn't actually give a detailed example of the specific use-case we were debating. And since I'm pretty sure he'll want to use the out-of-context answers on that other question as justification for why the above is "bad" I decided I needed to get opinions on this specific use-case.

© Programmers or respective owner

Related posts about best-practices

Related posts about php