奇怪的PHP字符串整数比较和转换

I was working on some data parsing code while I came across the following.

$line = "100 something is amazingly cool";
$key = 100;

var_dump($line == $key);

Well most of us would expect the dump to produce a false, but to my surprise the dump was a true!

I do understand that in PHP there is type conversion like that:

$x = 5 + "10 is a cool number"; // as documented on PHP manual
var_dump($x); // int(15) as documented.

But why does a comparison like how I mentioned in the first example converts my string to integer instead of converting the integer to string.

I do understand that you can do a === strict-comparison to my example, but I just want to know:

  • Is there any part of the PHP documentation mentioning on this behaviour?
  • Can anyone give an explanation why is happening in PHP?
  • How can programmers prevent such problem?

If I recal correcly PHP 'casts' the two variables to lowest possible type. They call it type juggling.

try: var_dump("something" == 0); for example, that'll give you true . . had that bite me once before.

More info: http://php.net/manual/en/language.operators.comparison.php

I know this is already answered and accepted, but I wanted to add something that may help others who find this via search.

I had this same problem when I was comparing a post array vs. keys in a PHP array where in my post array, I had an extra string value.

$_POST["bar"] = array("other");

$foo = array(array("name"=>"foobar"));

foreach($foo as $key=>$data){
    $foo[$key]["bar"]="0";
    foreach($_POST["bar"] as $bar){
        if($bar==$key){
            $foo[$key]["bar"]="1";
        }
    }
}

From this you would think that at the end $foo[0]["bar"] would be equal to "0" but what was happening is that when $key = int 0 was loosely compared against $bar = string "other" the result was true to fix this, I strictly compared, but then needed to convert the $key = int 0 into a $key = string "0" for when the POST array was defined as array("other","0"); The following worked:

$_POST["bar"] = array("other");

$foo = array(array("name"=>"foobar"));

foreach($foo as $key=>$data){
    $foo[$key]["bar"]="0";
    foreach($_POST["bar"] as $bar){
        if($bar==="$key"){
            $foo[$key]["bar"]="1";
        }
    }
}

The result was $foo[0]["bar"]="1" if "0" was in the POST bar array and $foo[0]["bar"]="0" if "0" was not in the POST bar array.

Remember that when comparing variables that your variables may not being compared as you think due to PHP's loose variable typing.