Friday, February 20, 2009

Good habit: in_array()'s third param

I got lulled into a relaxed state of mind with using in_array() to guard against input.

I had a validation method like:

$valid_types = array(0,1,2,3,4);

$type = 'string string string';

var_dump($type);
var_dump($valid_types);

var_dump(in_array($type, $valid_types));
var_dump(in_array($type, $valid_types, true));


Without executing it, what do you think happens?

I thought: bool(false), bool(false).

WRONG! in_array() does type conversion, so (int)"string string string" is 0; and yes, that's in our array.

So; to avoid surprises, always supply the strict param to in_array().

Its also a good thing to keep an eye on with code review.
Post a Comment