0

I have come across this php "error" on many occations but I've never stopped to thing about it. So this is me asking for someone to help me understand this:

$int = 0;
var_dump($int == "string");
var_dump(false == "string");
var_dump(false == $int);
3
  • 4
    us3.php.net/types.comparisons Commented Feb 11, 2016 at 13:33
  • Thanks found the answer in that url to clarify the answer in this case is: "This is true, because the string is casted interally to an integer. Any string (that does not start with a number), when casted to an integer, will be 0." Commented Feb 11, 2016 at 13:37
  • 1
    Possible duplicate of Why does (0 == 'Hello') return true in PHP? Commented Feb 11, 2016 at 13:39

3 Answers 3

2

The PHP Manual has a type Comparison Table in it, which gives you an idea of what happens when comparing variables of two different data types.

Your first example (a 'loose' comparison since it does not also check the data types of the two operands) implicitly converts the string on the left to an integer. Since it does not start with a number, the string is converted to the integer 0, which is equal to the integer 0.

Your second example compares not only the values but the types as well. Since the type is different, the comparison is false.

From this post

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

Comments

2

We use == for loose comparisons and === for strict comparisons.

$int = 0;
var_dump($int === "string"); //false
var_dump(false === "string"); //false
var_dump(false === $int); //false

3 Comments

I know how to fix it I was mearly asking why, I found the why in the link shared by @divyesh-savaliya
0 is an int, so in this case it is going to cast 'string' to an int. Which is not parseable as one, and will become 0. A string '0string' would become 0, and would match!
Same goes for false == 0. When parsing 0 as a boolean it becomes false. Same goes for true == anyothernumber
0

In PHP, the == operator checks that two values are equivalent - in other words, PHP will use type juggling where required, but things like 0 == false, 1 == '1' etc will be true.

To check that two values are identical (including type), use the === operator.

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.