php字符串比较意外类型杂耍

在比较一些字符串值时,我在 PHP中遇到了奇怪且意外的行为.当我希望它们返回false时,下面的前两个语句将返回true.最后一个语句按预期返回false.我知道PHPType Juggling,但我从文档中理解的是,当您比较两种不同的数据类型(如字符串和整数)时会发生类型杂耍.在下面的示例中,虽然两个文字都是字符串.这是否意味着当你在PHP中进行字符串比较时,它检查两个字符串以查看它们是否看起来像整数,如果是这样,则将它们两者转换为整数然后比较这些整数值.所以我的问题是在这种行为发生的条件下,字符串比较究竟如何在PHP中工作?

var_dump("10" == "10.0000");
var_dump("10" == "+10.");
var_dump("10" == "10 ");

#output
bool(true)
bool(true)
bool(false)

更新

因此,baba在comparison involves numerical strings以下的回答确实帮助我了解了正在发生的事情.函数is_numeric将返回给您,无论字符串是否被视为数字字符串.有趣的是,“10”不是数字字符串,而是“10”.我挖掘了PHP代码,我相信implementation of is_numeric在is_numeric_string_ex函数中.从那一点可以确切地知道PHP何时将字符串视为数字字符串.

解决方法

您将收到错误,因为空格的位置将返回true

var_dump("10" == " 10"); // true

所以,如果你跑

var_dump("10" == "10 "); //false

你实际运行的是因为它将被视为一个字符串

var_dump("10" == 0); //false

这是因为Type juggling会将“10”转换为0,这是在PHP Documentation

FROM PHP DOC

TRUE if $a is equal to $b after type juggling.

If you compare a number with a string or the comparison involves numerical strings,then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

如果你想欺骗类型杂耍

var_dump("10" == 0 + "10 ");  // true

This is Because

An example of PHP’s automatic type conversion is the addition operator ‘+’. If either operand is a float,then both operands are evaluated as floats,and the result will be a float. Otherwise,the operands will be interpreted as integers,and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...