PHP's isset() and arrays

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. $var = array('test' => null);
  2.  
  3. if (isset($var['test'])) {
  4.     echo 'set';
  5. } else {
  6.     echo 'not set, but the key exists';
  7. }

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

how using php with “?”….
please tel me examle source
thanx

dewa on 1/1/09

How do I using php? plz hlep
regards

Mulleteer on 9/12/10

hello, it seems it returns also false if key exist but is empty, that’s a little strange

dave on 12/2/10

owsome article….

pradeep on 9/27/12

Excelent!!!!

EH on 7/27/13

I am looking at this, need to say something like

If isset() …
echo “Died In: “,$p->getYearDied();

jessica on 10/25/13

Comments are not open at this time.