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

704 阅读2分钟

这是我参与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() 和 array_search() 默认都是松散比较,相当于==,即得到 true。

严格比较

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

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 -

作者:架构精进之路,十年研发风雨路,大厂架构师,CSDN 博客专家,专注架构技术沉淀学习及分享,职业与认知升级,坚持分享接地气儿的干货文章,期待与你一起成长。
关注并私信我回复“01”,送你一份程序员成长进阶大礼包,欢迎勾搭。

Thanks for reading!