Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if($val) vs. if($val != "") vs. if(!empty($val)) -- which one?

I see a lot of people using a variety of different methods to check whether of a variable is empty, there really seems to be no consensus. I've heard that if($foo) is exactly the same as if(!empty($foo)) or if($foo != ""). Is this true?

I realize it's a really simple question, but I'd really like to know. Are there any differences? Which method should I use?

like image 283
Avicinnian Avatar asked Sep 12 '11 08:09

Avicinnian


1 Answers

Difference between bare test and comparison to empty string

if($foo != "") is equivalent to if($foo) most of the time, but not always.

To see where the differences are, consider the comparison operator behavior along with the conversion to string rules for the first case, and the conversion to boolean rules for the second case.

What I found out is that:

  • if $foo === array(), the if($foo != "") test will succeed (arrays are "greater than" strings), but the if($foo) test will fail (empty arrays convert to boolean false)
  • if $foo === "0" (a string), the if($foo != "") test will again succeed (obviously), but the if($foo) test will fail (the string "0" converts to boolean false)
  • if $foo is a SimpleXML object created from an empty tag, the if($foo != "") test will again succeed (objects are "greater than" strings), but the if($foo) test will fail (such objects convert to boolean false)

See the differences in action.

The better way to test

The preferred method to test is if(!empty($foo)), which is not exactly equal to the above in that:

  1. It does not suffer from the inconsistencies of if($foo != "") (which IMHO is simply horrible).
  2. It will not generate an E_NOTICE if $foo is not present in the current scope, which is its main advantage over if($foo).

There's a caveat here though: if $foo === '0' (a string of length 1) then empty($foo) will return true, which usually is (but may not always be) what you want. This is also the case with if($foo) though.

Sometimes you need to test with the identical operator

Finally, an exception to the above must be made when there is a specific type of value you want to test for. As an example, strpos might return 0 and also might return false. Both of these values will fail the if(strpos(...)) test, but they have totally different meanings. In these cases, a test with the identical operator is in order: if(strpos() === false).

like image 55
Jon Avatar answered Oct 08 '22 18:10

Jon