Why isset() in PHP can be misleading

by Martin Westin in

I thought this was worth noting even though a comment on php.net explain it very well. You can not rely on isset() for associative arrays unless you know for a fact you are checking an array.

That is: in case the variable you think is an array is in fact a string you will be in trouble. The reason being that you can access characters in a string using array notation. And since PHP is dynamically typed you can end up checking a string by mistake (or by malicious data from the browser).

Since CakePHP is full of associative arrays this is bound to happen to most people sooner or later. I have stumbled on this once when I was dealing with serialized data. I used isset() to check wether the data was serialized or not.

Here is a little example. Both checks will return true.

 'some data'
$test2 = array(
	'data' => array('key'=>'val')

echo isset($test['data']['key']);
echo ' - ';
echo isset($test2['data']['key']);

There are a number of ways to get around this problem. One if to use array_key_exists(). Another is to use is_array() alongside isset().