前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >为啥PHP in_array(0,['a', 'b', 'c']) 返回为true?

为啥PHP in_array(0,['a', 'b', 'c']) 返回为true?

作者头像
架构精进之路
发布2020-08-17 15:51:08
1.6K0
发布2020-08-17 15:51:08
举报
文章被收录于专栏:架构精进之路架构精进之路

0、 问题背景

在具体PHP编码过程中,总会出现一些我们认为不可能的情况,如下几例:

代码语言:javascript
复制
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'这个字符串。那怎么解释上述的返回结果呢?

1、 类型转换

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

代码语言:javascript
复制
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.

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

代码语言:javascript
复制
echo intval('abc');  // 输出0

inarray()和arraysearch()默认都是松散比较,相当于==,即得到true。

2、 严格比较

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

代码语言:javascript
复制
in_array(0, ['a', 'b', 'c'], true)      // 返回bool(false)
array_search(0, ['a', 'b', 'c'], true)  // 返回bool(false)
0 === 'abc'                             // 返回bool(false)

3、 false 与 null

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

代码语言:javascript
复制
in_array(null, ['a', 'b', 'c']) // 返回bool(false)
in_array(false, ['a', 'b', 'c']) // 返回bool(false)

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

4、 数组中有true

另一个看起来比较奇怪的现象

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

总结

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

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-04-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 架构精进之路 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档