2

Possible Duplicate:
Double equals and tripple equals in php

I am trying to test against various types of 'empty' variables that aren't empty. One situation that comes up a lot is

if a string equals "''" (i.e., two single-quote characters) then do xyz, else do abc

I have variables of different types, which may be 0, '0' (i.e, the character '0', ASCII 48, as opposed to the value 0), and "" (the empty string). ALL of these evaluate the same as "''", the string containing two single-quotes. Clearly, they are not the same! One is a string of two characters -- ASCII 39, ASCII 39 -- and the others may be 0, ASCII 48, etc.

I've come up with work-arounds using is_numeric(), etc., but I can't help but thinking there must be a better way. What is the preferred method to handle this sort of thing?

Thanks much for your patience in what must seem to be a very naïve question.

Community
  • 1
  • 1
david furst
  • 329
  • 4
  • 17

3 Answers3

5

You can also use if(!empty($string)) http://php.net/manual/en/function.empty.php for more info.

Charles
  • 1,121
  • 19
  • 30
  • the "if(!statement)" is basically saying "if not (statement)" – Charles Dec 13 '12 at 02:13
  • empty() is not exactly same as checking if a given variable is equal to "". empty() also returns TRUE if a given array is empty, a string has no content, or the given variable contains a numerical zero. – AKS Dec 13 '12 at 02:47
3

You can use the identical operator (===) to check on the type and on the value. See http://php.net/manual/en/language.operators.comparison.php for more information.

tmuguet
  • 1,165
  • 6
  • 10
  • That's great! and so simple too. thanks very much. I'd already tried empty(), but as ayesh k mentions above, it returns true in all cases, but the === seems to work. – david furst Dec 13 '12 at 20:46
1

If you do an identical check

if ($string === '')

then you will get the result you are after.

See this previous SO answer for more details on the types of operators and what effect they have.

Community
  • 1
  • 1
Laurence
  • 58,936
  • 21
  • 171
  • 212