1

I'm declaring a var $t and assigning it a value of 0. I then reassign $t a new value of test. It then appears that $t is both 0 AND test. Here's the code:

$t = 0;
$t = "test";

if($t == 0 && $t == "test"){
    echo "unexpected";
}else{
    echo "expected";
}

The output is:

"unexpected"

Can someone please explain what is going on here? Is $t really two different values (0 and test) at the same time or am I missing something?

Allen S
  • 3,471
  • 4
  • 34
  • 46
  • I'm not sure why, but if you make the code just: $t = 'test'; if($t == 0) {echo 'yes';} it echos yes. So apparently the string evaluates to the same value as 0. – imkingdavid Feb 02 '15 at 06:01
  • 1
    Visit: http://stackoverflow.com/questions/672040/comparing-string-to-integer-gives-strange-results – Gaurav Dave Feb 02 '15 at 06:02

4 Answers4

4

This "strange" behaviour results in because of PHP's type juggling. Since you're using loose comparison == to compare to an integer 0 the string test is being converted to an integer, which results in conversion to 0. See the Loose comparison == table. There in the row with the string php you'll see that it equals to the integer 0, which applies to all strings.
You should be using strict (type) comparison operators, i.e. ===.

Havelock
  • 6,913
  • 4
  • 34
  • 42
0

You're not appending or concatenating so it shouldn't be. Try the identical comparison operator instead.

if($t === 0 && $t === "test"){
   ....
}
EternalHour
  • 8,308
  • 6
  • 38
  • 57
0

PHP MANUAL STATES:

The value is given by the initial portion of the >string. If the string starts with valid numeric >data, this will be the value used. Otherwise, the >value will be 0 (zero). Valid numeric data is an >optional sign, followed by one or more digits >(optionally containing a decimal point), >followed by an optional exponent. The >exponent is an 'e' or 'E' followed by one or >more digits.

http://il.php.net/manual/en/language.types.string.php#language.types.string.conversion

So $t == 0 is true. You have to use strict comparison ===

Robert
  • 10,126
  • 19
  • 78
  • 130
0

Hey buddy use "===" operator for your comparison.

In php we can assign any value to a simple variable, it holds numeric, float, character, string, etc.

So always use "===" operator for unique or same value matching.