比较PHP中的不同字符串与==返回true [英] Comparing different strings in PHP with == returns true

查看:222
本文介绍了比较PHP中的不同字符串与==返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是调试一个脚本,发现if语句没有按照我的预期方式工作。

I was just debugging a script and found that an if-statement wasn't working the way I expected it to.

var_dump("6064365413078728979" == "6064365413078728452");
die();

上述代码将导致以下结果:

The code above will result in the following:

bool(true)

运算符它按预期工作。任何人都有任何想法为什么?

With the === operator it works as expected. Anyone got any ideas why?

我使用PHP版本5.3.13与wamp安装在x64 Windows机器上。

I'm using PHP Version 5.3.13 with a wamp installation on a x64 windows machine.

推荐答案

<?php
$a=6064365413078728979;
$b=6064365413078728452;
echo $a."<br>".$b;
//var_dump( $a==$b );
die();
?>

当你运行那个,然后在你的机器上可能超过一个数字的限制,数字比较发生。尝试上面的脚本,看到$ a的价值可能会不同于你给的价值。

When you run that, then on your machine that might be exceeding limit for a number and that is a numeric comparison taking place. Try the script above and see value for $a will probably be different than the value you gave.

这就是为什么当两个数字比较他们是相等的。因此,请使用其他人建议的 ===

That is why when both are compared numerically they are equal. Hence use === as suggested by others

编辑:基于@ Axel的建议。

Explanation based upon @Axel's Advice.

PHP手册说明


浮点的大小是平台相关的,尽管最大值为
〜1.8e308,精度约为14位十进制数是常见的
值(64位IEEE格式)。

The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).

并且这个网站提供和解释溢出现象和一个小的PHP代码来测试你的系统的整数和浮动范围。了解您的服务器上的限制很可能解释为什么提供流出现

And this website is offering and explanation on the Overflow phenomenon and a small php code to test your system's integer and float range. Getting to know the limit on your servers will most probably explain it best why the offerflow occured

这篇关于比较PHP中的不同字符串与==返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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