Php 如果指针为0,in_数组返回true

Php 如果指针为0,in_数组返回true,php,arrays,conditional-statements,Php,Arrays,Conditional Statements,我对数组中的函数有问题。下面的测试返回true: in_array(0, array('card', 'cash')) 这怎么可能,我怎么能阻止它 然而 in_array(null, array('card', 'cash')) 返回false在PHP中,将任何不以数字开头的字符串转换为数字将导致0。这正是将0与某个字符串进行比较时发生的情况。有关如何在各种类型之间进行比较的详细信息,请参见 使用的第三个参数(将其设置为true)以避免松散的类型比较 in_array(0, array('c

我对数组中的
函数有问题。下面的测试返回
true

in_array(0, array('card', 'cash'))
这怎么可能,我怎么能阻止它

然而

in_array(null, array('card', 'cash'))

返回
false

在PHP中,将任何不以数字开头的字符串转换为数字将导致
0
。这正是将
0
与某个字符串进行比较时发生的情况。有关如何在各种类型之间进行比较的详细信息,请参见

使用的第三个参数(将其设置为
true
)以避免松散的类型比较

in_array(0, array('card', 'cash'), true) === false

答案可以是将
0
转换为字符串,因此:

in_array((string) 0, array('card', 'cash'))

请记住,
0
可能是一些变量,因此强制转换可能会有所帮助。

当您在
中比较\u数组时
比较不兼容的数据类型时,字符串转换为int 这意味着
现金
转换为
0

这都是因为类型转换

你有两个选择

一,。类型铸造

in_array(string(0), array('card', 'cash'))) === false;
2.在数组中使用
第三个参数
true
匹配数据类型

in_array(0, array('card', 'cash'), true) === false;

请参见

您可以通过使用“strict”参数来防止:

var_export(in_array(0, array('card', 'cash'), true));

var_export(in_array(null, array('card', 'cash'), true));
在这两种情况下都返回false


(int)0英寸(int)“卡片”?松散键入。。。您将数字与字符串进行比较,因此字符串将转换为数字,在本例中为0,0==0。使用可选的严格参数好吧,这就是我需要的答案。非常感谢。哎呀!!回答这个问题有点晚了。。
If the third parameter strict is set to TRUE then the in_array()
function will also check the types of the needle in the haystack.