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.

2
  • 1
    (int) 0 in (int)'card'? May 28, 2013 at 8:53
  • 4
    LOOSE TYPING... you're comparing number with string, so the string is converted to a number, giving 0 in this case, and 0 == 0. Use the optional STRICT argument
    – Mark Baker
    May 28, 2013 at 8:54

4 Answers 4

24

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
1
  • All right, that's the answer that I need. Thank you !
    – hsz
    May 28, 2013 at 8:55
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

1
  • OOPS !! bit late to answer that .. May 28, 2013 at 8:59
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.
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.