9

I have an issue with in_array function. Test below returns true:

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

How is it impossible, how can I prevent it ?

However

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

returns false.

4

4 回答 4

24

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

使用第三个参数(将其设置为truein_array来避免松散的类型比较。

in_array(0, array('card', 'cash'), true) === false
于 2013-05-28T08:53:37.573 回答
7

when you compare in in_array string is converted to int while comparing incompatible data types it means cashor card is converted to 0

This is all because of type casting

You have 2 options

1 . Type casting

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

2 .Use third parameter on in_array to true which will match the datatypes

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

see documentation

于 2013-05-28T08:58:43.473 回答
2

You can prevent it by using the 'strict' parameter:

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

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

returns false in both cases.

From the docs to in_array()

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.
于 2013-05-28T08:59:46.683 回答
0

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

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

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

于 2013-05-28T08:53:51.943 回答