加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php字符串比较,为什么要转换为float

发布时间:2020-12-13 17:30:43 所属栏目:PHP教程 来源:网络整理
导读:我遇到过这段代码 ?php$a = md5('240610708');$b = md5('QNKCDZO');echo "$an";echo "$bn";echo "n";var_dump($a);var_dump($b);var_dump($a == $b); 这将评估2个字符串,它们可以是数字0exxxxxx.我理解,如果在数字上下文中使用任何一个,那么该字符串将被
我遇到过这段代码

<?php

$a = md5('240610708');
$b = md5('QNKCDZO');

echo "$an";
echo "$bn";
echo "n";
var_dump($a);
var_dump($b);
var_dump($a == $b);

这将评估2个字符串,它们可以是数字0exxxxxx.我理解,如果在数字上下文中使用任何一个,那么该字符串将被视为一个数字,由http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion确认

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

If the string does not contain any of the characters ‘.’,‘e’,or ‘E’
and the numeric value fits into integer type limits (as defined by
PHP_INT_MAX),the string will be evaluated as an integer. In all other
cases it will be evaluated as a float.

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.

我只是不确定为什么==当双方都是字符串类型时触发数字比较.

解决方法

TL; DR

这是PHP中字符串“智能”比较的结果.是的,它不是你所期望的,但是现在 – 它是如何实现的.

深层发掘

保持比较

为了实现这个原因,你需要研究PHP源代码(更好或更好).在PHP中,有一个用于处理比较的东西,如compare_function.它包含不同类型参数的不同情况.所以,对于字符串,它是:

case TYPE_PAIR(IS_STRING,IS_STRING):
    zendi_smart_strcmp(result,op1,op2);
    return SUCCESS;

TYPE_PAIR,就像其他任何东西一样,只是一个宏.

走得更深

从上一步开始,我们现在转向zendi_smart_strcmp.比较两个字符串是PHP的“聪明之物”.我们在这里:

if ((ret1=is_numeric_string_ex(Z_STRVAL_P(s1),Z_STRLEN_P(s1),&lval1,&dval1,&oflow1)) && (ret2=is_numeric_string_ex(Z_STRVAL_P(s2),Z_STRLEN_P(s2),&lval2,&dval2,&oflow2))) 
{
    //compare as two numbers,I've omitted this
}
else 
{
    string_cmp: //yes,yes,we're using goto
    Z_LVAL_P(result) = zend_binary_zval_strcmp(s1,s2);
    ZVAL_LONG(result,ZEND_NORMALIZE_BOOL(Z_LVAL_P(result)));
}

在省略的代码中还有一部分用于确定结果是长还是双 – 但这是无关紧要的,因为我们已经知道是什么导致比较为浮点数:只要字符串可以被视为数字,PHP将使用它来产生比较 – 和 – 是的,这是预期的(所以,是的,当使用==运算符时,字符串“1000”等于“1e3”,对于“255”和“0xFF”则相同 – 它们不包含“e”(指数)部分,但仍然是平等的)

例如,您可以限制案例:

var_dump("0e8" == "0e6"); //true

所以不需要处理md5哈希.如果将其作为数字进行比较,则为真(因为两个操作数都是有效的浮点数,并且0 x 10 ^ 8 == 0 x 10 ^ 6).但它们与字符串不同.因此,您的直接解决方案是 – 使用===运算符进行比较:

var_dump("0e8" === "0e6"); //false

是的,这在PHP中是一个令人困惑的事情 – 因为它并不明显(至少有争议).但这就是目前的工作方式.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读