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.

hakre
  • 193,403
  • 52
  • 435
  • 836
hsz
  • 148,279
  • 62
  • 259
  • 315

4 Answers4

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
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
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

alwaysLearn
  • 6,882
  • 7
  • 39
  • 67
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.
dennis
  • 592
  • 5
  • 10
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.

hsz
  • 148,279
  • 62
  • 259
  • 315