Ben Ben - 3 years ago 89
PHP Question

PHP's in_array bevahior surprises me

While validating a dynamic saving method in a controller I wanted to make sure a given case only accepts 0 and 1 as valid values. When I tried to manipulate the input form, submitting 'aaa' as a value the following still returns true. Why is that?

var_dump(in_array('aaa', [0, 1])); // true, I was expecting it to return false

Answer Source

You need to use the "strict" setting, to force the function to check the types of the elements as well:

var_dump(in_array('aaa', [0, 1], true)); states

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.

The reason it returns true is because a string is truthy, and so is 1.

if( "aaa" ){ echo "you will see me"; }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download