20

Possible Duplicate:
Why does PHP consider 0 to be equal to a string?

I have this piece of code:

$o['group'] = "prueba";
if( $o['group'] == 0){
    die("test");
}

Why it print test? how can be possible that a string is equal to zero?

2
  • 1
    In PHP, the empty string, and the string "0" will both be equal to zero with the equality operator (==). Commented Dec 29, 2011 at 18:43
  • 6
    @MichaelMior: And any other string which cannot be converted to a number. Commented Dec 29, 2011 at 18:44

2 Answers 2

18

if you want it to exactly match the string try using the exact typof three equal signs like so
if( $o['group'] === 0){
the == will always evaluate to true when comparing a string to a integer of 0

'a string' == 0 also evaluates to true because any string is converted into an integer when compared with an integer. If PHP can't properly convert the string then it is evaluated as 0. So 0 is equal to 0, which equates as true.

From here

Sign up to request clarification or add additional context in comments.

2 Comments

Still wrong. '0.1e2' == 0 is false although (int) '0.1e2' === 0 is true. The string content determines which data type (int or float) the string is converted to.
Yes, this is still wrong. Only works if $o['group'] == '0'
10

Use comparison operator with type check "===". Look here for the example http://php.net/manual/en/language.operators.comparison.php and explanation why non-numerical string compared to zero always returns true.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.