Testing for not true vs true
# November 12, 2012 at 10:04 am
I was told once a long time ago in a classroom far, far away that testing for true was a bit more efficient than testing for not true (!$some_var).
Just curious if this is true, or if anyone even has this in the back of their mind when creating their code structure.
It has, for some reason, stuck with me. I will often test for true rather than not-true if at all possible.
I have a feeling I will be face-palming myself soon haha# November 12, 2012 at 1:14 pm
This reply has been reported for inappropriate content.
JoniGuiro, if you are referring to testing as such I know what you mean: $somevar === FALSE
(PS… awesome avatar haha)
I think it was explained to me that it’s a bit of a double-test… ‘is it not-true?’. Compared to just ‘is it true?’. So if possible, test for true, rather than not-true.
I highly doubt it makes any difference (noticeably) at all. I was just curious if anyone else had this strange logic in their head ;)# November 12, 2012 at 1:34 pm
@fooman, that’s right, it’s a double test.
Let’s say `$somevar = false`. If you do:
if( $somevar === false )
…what you’re really writing is
if( false === false )
So you can just do
if( !$somevar )
You’ll see this a lot in JS where people are checking something:
Another reason you’ll want to use `!` is because it checks for more than just `false`. You may be looking through an array looking for a value and it could return:
- empty string
None of those things === false, so you wouldn’t be able to catch them. If you used `!$somevar` then you are golden!
You must be logged in to reply to this topic.