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.

SS44
  • 837
  • 2
  • 10
  • 26
  • 2
    nvm found the answer here: http://stackoverflow.com/questions/9257685/weird-php-string-integer-comparison-and-conversion – SS44 Feb 27 '12 at 16:08

4 Answers4

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).

spencercw
  • 3,320
  • 15
  • 20
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

lamplightdev
  • 2,041
  • 1
  • 20
  • 24
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.

Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
-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

vdegenne
  • 12,272
  • 14
  • 80
  • 106
  • 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. – Josh Feb 27 '12 at 16:22