奇怪的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?
我正在研究一些数据解析代码,而我遇到了以下内容。 p>
我们大多数人都希望转储产生 我知道在PHP中有类似的类型转换: p>
但为什么我在第一个例子中提到的比较将我的字符串转换为整数而不是将整数转换为 串。 p>
我明白你可以对我的例子进行 $ line =“100令人惊讶的酷”;
$ key = 100;
var_dump($ line == $ key);
code> pre>
false code>,但令我惊讶的是转储是
true code> strong>! p>
$ x = 5 +“10是一个很酷的数字” ; //如PHP手册中记载的
var_dump($ x); // int(15),如文档所示。
code> pre>
=== code>严格比较,但我只是想知道: p>
\ n
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.