最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • 为啥 PHP in_array(0,['a', 'b', 'c']) 返回为 true?

    正文概述 转载于:掘金(架构精进之路)   2021-08-20   581

    这是我参与8月更文挑战的第20天,活动详情查看:8月更文挑战

    问题背景

    在实际 php 编码过程中,总会出现一些我们意料之外的情况,如以下几例:

    in_array(0, ['a', 'b', 'c']) // 返回bool(true),相当于数组中有0
    array_search(0, ['a', 'b', 'c']) // 返回int(0),相当于是第一个值的下标
    0 == 'abc' // 返回bool(true),相当于等值
    

    但是,直观上看, 0 并没有包含在['a', 'b', 'c']数组中,也不会等于'abc'这个字符串。那怎么解释上述的返回结果呢?

    类型转换

    究其原因:在数据比较前,PHP 做了类型转换。引用 PHP 官网关于“String conversion to numbers”解释如下:

    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, thiswill 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.
    

    文章开篇例子中,string 类型数据第一个字符不是数字,就会转换为 0,例如:

    echo intval('abc');  // 输出0
    

    复制代码

    严格比较

    那怎么得到我们预期的结果呢?推荐使用严格比较,如下所示:

    in_array(0, ['a', 'b', 'c'], true)      // 返回bool(false)
    array_search(0, ['a', 'b', 'c'], true)  // 返回bool(false)
    0 === 'abc'                             // 返回bool(false)
    

    false 与 null

    那么,如果用 false 和 null 与字符串数组比较,结果会如何呢?

    in_array(null, ['a', 'b', 'c']) // 返回bool(false)
    in_array(false, ['a', 'b', 'c']) // 返回bool(false)
    

    null 与 false 做比较值,字符串数组是不会转换为 int 型的。

    数组中有 true

    另一个看起来比较奇怪的现象,如下图所示:

    in_array('a', [true, 'b', 'c'])     // 返回bool(true),相当于数组里面有'a'
    array_search('a', [true, 'b', 'c']) // 返回int(0),相当于找到了字符串'a'
    

    复制代码

    总结

    PHP 语言本身是弱类型语言,为了便于应用处理,会做一些类型转换操作。

    同时为了保证转换精度准确性等问题,PHP 官方建议:不要将未知的分数强制转换为 integer,这样有时会导致不可预料的结果

    - END -

    Thanks for reading!


    起源地下载网 » 为啥 PHP in_array(0,['a', 'b', 'c']) 返回为 true?

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元