3

I'm a little bit confused about truth in PHP.

My understanding is that 0 evaluates to false, and non-empty strings (unless the string is "0") evaluate to true.

This is as I expect:

var_dump((bool) 0);              // prints "boolean false"
var_dump((bool) 'someString');   // prints "boolean true"

But then I am surprised by the following result:

var_dump((0=='someString'));     // prints "boolean true"

My question is, why does 0=='someString' evaluate to true?

stephen.hanson
  • 9,014
  • 2
  • 47
  • 53
  • Nanne - I understand the difference between those operators. This is a question about how true/false is evaluated in `==` comparisons of different types. Different IMO. – stephen.hanson Dec 17 '13 at 16:32
  • php is a soft typing language, it converts types on the fly 0 can be both a string and an integer depending on where its used with no changes made – Jeff Hawthorne Dec 17 '13 at 16:35
  • 1
    Error in your title."someString" == 0 does NOT evaluate to true since it's a string compare, but 0=="somestring " does since it is a numeric compare. – Digital Chris Dec 17 '13 at 16:41

1 Answers1

8

When using the comparison (==) operator strings will be converted to an integer when compared to another integer. This is because of type juggling in PHP. So "someString" evaluates to zero because it is converted to an integer and has no leading digits. If you use the the identical operator (===) type conversions are not done so "someString" is treated a literal string and your statement will then evaluate to false.

The following will evaluate to false when type juggling is performed. Everything else will be evaluated as true:

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)
John Conde
  • 217,595
  • 99
  • 455
  • 496