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.
Casting any string that doesn't start with a digit to a number results in 0 in PHP. And this is exactly what happens when comparing 0 with some string. See the PHP docs for details about how comparisons between various types are done.
Use the third argument (set it to true) of in_array to avoid loose type comparison.
in_array(0, array('card', 'cash'), true) === false
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
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.
An answer can be casting 0 to string, so:
in_array((string) 0, array('card', 'cash'))
Keep in mind that 0 can be some variable, so casting can be helpful.