1

Anyone know why in php

var_dump( "cat" == 0 );

Evaluates to true? Also I realize:

var_dump( "cat" === 0 );

has the intended result, but curious as to why the first case would be true. Also this is php 5.3.

1

4 Answers 4

2

The string is being implicitly converted to an integer. See the documentation:

If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).

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

Comments

1

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.

Comments

1

Because you are implicitly casting the string to an integer, and as the string does not contain numbers it is cast to a 0

Comments

-1

"cat" is juggling to 0 as an integer, that is why it is true

but if you typed

var_dump( "01" == 0 );

it would have been false because 1 is not equals 0

1 Comment

Your expression actually evaluates to true. cat1 is converted to 0. The string needs to begin with an integer to be converted into that integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.