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
.
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
.
when you compare in in_array
string is converted to int while comparing incompatible data types
it means cash
or 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
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.
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.
答案可以转换0
为字符串,因此:
in_array((string) 0, array('card', 'cash'))
请记住,这0
可能是一些变量,因此强制转换可能会有所帮助。