Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in_array returns true if needle is 0 [duplicate]

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.

like image 873
hsz Avatar asked May 28 '13 08:05

hsz


2 Answers

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
like image 92
ThiefMaster Avatar answered Nov 12 '22 02:11

ThiefMaster


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

like image 7
alwaysLearn Avatar answered Nov 12 '22 03:11

alwaysLearn