将字符串与整数比较会产生奇怪的结果 [英] Comparing String to Integer gives strange results

查看:106
本文介绍了将字符串与整数比较会产生奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很困惑,为什么这个操作工作。有人可以解释吗?

  $ test1 =d85d1d81b25614a3504a3d5601a9cb2e 
$ test2 =3581169b064f71be1630b321d3ca318f;

if($ test1 == 0)
echoTest 1 is Equal !?;
if($ test2 == 0)
echoTest 2 is Equal !?;

//返回:Test 1是Equal !?



为了说明,我试图比较字符串0 code>到 $ test 变量。我已经知道修复代码我可以把($)$ 0 / p>

我想知道这是一个PHP错误,一个服务器错误,还是某种有效的操作。根据 http://us3.php.net/types.comparisons ,此应该

编辑很明显,它确实提到字符串和0之间的松散比较是真的。但我仍然不知道为什么。



编辑2:我修改了我的问题,为什么 $ test2 的价值3581169b064f71be1630b321d3ca318f不工作?

解决方案

从PHP手动


字符串转换为数字



当在
数值上下文中对字符串求值时,结果值
和类型如下确定。



如果它包含任何
字符'。','e'或'E',则被评估为
float。
否则,它将被计算为
整数。



该值由字符串的初始
部分给出。如果字符串
以有效的数字数据开头,则该
将是使用的值。否则,
值将为0(零)。有效的数字
数据是一个可选符号,后跟
一个或多个数字(可选的
包含一个小数点),紧跟
一个可选的指数。指数
是一个'e'或'E',后跟一个或
个数字。



I'm really confused as to why this operation works. Can someone explain it?

$test1 = "d85d1d81b25614a3504a3d5601a9cb2e";
$test2 = "3581169b064f71be1630b321d3ca318f";

if ($test1 == 0)
  echo "Test 1 is Equal!?";
if ($test2 == 0)
  echo "Test 2 is Equal!?";

// Returns: Test 1 is Equal!?

For clarification, I am trying to compare the string "0" to the $test variables. I already know to fix the code I can just enclose (as I should have) the 0 in ""s

I'm wondering if this is a PHP bug, a server bug, or somehow a valid operation. According to http://us3.php.net/types.comparisons this should not have worked.

Edit: Scratch that, apparently it does mention that Loose comparisons between string and 0 is true. But I still don't know why.

Edit 2: I've revised my question, why does the $test2 value of "3581169b064f71be1630b321d3ca318f" not work?

解决方案

From the PHP manual:

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be evaluated as an integer.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

这篇关于将字符串与整数比较会产生奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆