duandingcu7010 2012-02-13 08:50
浏览 48
已采纳

奇怪的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?
  • 写回答

2条回答 默认 最新

  • duan36000 2012-02-13 08:57
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?