duanchigeng4313 2015-03-23 11:36
浏览 20
已采纳

如何将字符串与零比较为真?

php -a
Interactive shell

php > var_dump("some" == 0);
bool(true)
php > var_dump("some" == false);
bool(false)
php > var_dump("some" == true);
bool(true)
php > var_dump(false == 0);
bool(true)

My question is simple. What is the reasoning behind ("some" == 0) === true? I understand that due to the weak typing the operands are converted to something comparable. But in this particular example it's against how I understand it.

If the zero would be converted to string it would be:

php > var_dump("some" == "0");
bool(false)

If it was converted to bool, it would be:

php > var_dump("some" == false);
bool(false)

Only sensible explanation is:

php > var_dump(intval("some"));
int(0)
php > var_dump(intval("some") == 0);
bool(true)

But that's certainly not what I or anyone would expect. Especially because any string would be turned to zero (and that potentially means false in any comparison).

Why is it this way?

Update:

My question was more about "why" not "if" or "how", sorry if that was not quite obvious. And I think I found my answer in Why PHP casts two numerical strings to numbers before [loosely] comparing them?

  • 写回答

1条回答 默认 最新

  • dongzhang1864 2015-03-23 11:40
    关注

    Simples

    php > var_dump("some" == 0);
    

    The string "some" is cast to an integer for comparison with an integer, and will be cast to a 0 in this case.

    0 == 0 is true

    If the string "13 monkeys" was cast to an integer, it would be a value of 13

    php > var_dump("13monkeys" == 0);
    

    13 == 0 is false

    The rules for casting a string to a number are explained in the PHP docs

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记