dongzhong5756 2014-11-30 18:40
浏览 56
已采纳

PHP + JavaScript:将空字符串与0进行比较时,幕后会发生什么

Because of loose typing, PHP has to cast both compared variables to the same type, if they aren't yet. What happens behind the scenes for this comparison:

$v = "" == 0;

It returns true. If the type of the first variable is internally casted to the type of the second variable, I can understand it:

$v = (int)"" === 0;

But if it were so, the inverse comparison should fail:

$w = 0 == "";

because

(string)0 = "0"

which is obviously not equal to "".

but it returns true, as well.

The same behavior can be observed with JavaScript.

So now I am asking myself: what happens there?! The only explanation for me is that both variables are casted to boolean. But in this case, ["X"] == "X" should return true, but it obviously doesn't. So, what's the magic to assume "" equal 0?

  • 写回答

3条回答 默认 最新

  • doulu0266 2014-11-30 18:49
    关注

    In PHP when using the equal it will convert the input so that the following are all equal:

    0 == "" == false
    

    Which all will pass an empty() check.

    If you want to check the exact type use === instead. To answer your comment, array() is not a variable, but rather a data structure, that is why it fails the == check but passes the empty() check.

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

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来