PHP's isset() and arrays

Jun 01 2008

Earlier this week I learned that isset() behaves a little differently than I had expected when dealing with arrays. Now I already knew that isset() would return false on a variable not existing, or being set to null. However, I was not expecting it to return false on an array key existing and being set to null.

Show Plain Text
  1.  
  2. $var = array('test' => null);
  3.  
  4. if (isset($var['test'])) {
  5.     echo 'set';
  6. } else {
  7.     echo 'not set, but the key exists';
  8. }
  9.  

The above example illustrates something that will be confusing and bewildering if you don’t know that isset() returns false on array keys with null values. My specific case was creating conditionals based on arrays having certain keys regardless of their current value. In the end a workable solution for me was to use array_key_exists() it will return true regardless of the value assigned to the key.


Comments

There are no Comments, Be the First!


Have Something to say?

*
* (Never published, I promise)
* You can use Textile markup, but be reasonable

Recent Artwork

  • Shuriken 2
  • Clumsy Penguins
  • Balloon Animals
  • Metal in the air! (vertical)
  • Cleavers
  • Waiting