duanfangbunao36970 2013-08-16 09:02
浏览 45
已采纳

怎么来的(' - '== 0)===是真的吗?

I was working here with some exploded string walks:

array_walk($data, function(&$value)
{
    // Transform numerics into appropriate type numbers
    if (is_numeric($value))
    {
        $value = substr_count($value, '.') == 1 ? (float) $value : (int) $value;
    }

    // Transform dashes into nulls
    if ($value == '-')
    {
        $value = null;
    }
});

to transform values into their appropriate types, and some special character handling.

Where I stumbled upon an interesting, huh, bug?

The Bug

I was amazed, that each entry, that had it's initial value as string(1) '0' ended up being a null.

At first, I thought that the problem relies in (float) and (int) typecasts, though, after debugging:

var_dump((float) '0', (int) '0');

I saw that's not the case, getting the expected result:

float(0)
int(0)

It took me a while, to attempt to debug the, what at the moment appeared to be an obvious, weak type check, but, once I did, I was shocked:

var_dump('-' == 0);

The above expression appears to be:

bool(true)

Now, while writing, I thought I should debug some more, so:

var_dump( '=' == 0 );
var_dump( 'What a lovely nonsense?' == 0 );
var_dump( 0 == 'DAFUQ?' ); // maybe it's because of order? It's PHP, world of miracles, you know...

And, every expression listed above is bool(true).

Okay, maybe that's because internally, mystically PHP casts the expression into a (bool)?

var_dump( (bool) '-' == 0 );

No:

bool(false)

So, so, so...

I made a test-case here: http://codepad.org/smiEvsDj
The problem exists in 5.2.5 (codepad), also in 5.4.3 (friend) and also in 5.4.17 (my actual environment).

What is the reason behind this feature / bug / what-the-F-actually-is-this?

  • 写回答

2条回答 默认 最新

  • douli6605 2013-08-16 09:12
    关注

    You have stumbled upon one of the major complaints that people have about PHP as a language: The fact that the "==" operator is not transitive.

    Any string "foo" == TRUE, because the PHP people wanted this to work:

    if ($string) {
        // do something if $string is set
    }
    

    Yet, converting a string to a number (which PHP always tries to do when you use "=="), "foo" == 0!

    Of course, TRUE != 0. That is a major pain when dealing with PHP, it's not logical, but it's reality.

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

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况