Why isset() in PHP can be misleading

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.

<?php
$test = array(
	'data' => '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().

Share and Enjoy:
  • Digg
  • StumbleUpon
  • del.icio.us
  • Twitter
  • Google Bookmarks
  • email
  • Technorati

Add Your Comments

Disclaimer
Your email is never published nor shared.
Required
Required
Tips

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <ol> <ul> <li> <strong>

Ready?