Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is there a way to check if an array index exists or is null? isset() doesn't tell you whether the index doesn't exist or exists but is null. If I do : isset($array[$index]) || is_null($array[$index]) it won't work because if the index doesn't exist is_null will crash.

How can I check this please? Also is there a way to check only if something exist, no matter if it is set to null or not?

share|improve this question
Try !empty to check. – Devang Rathod Mar 9 at 11:45
Wouldn't the same if statements in a nested if structure work fine? – Chris Mar 9 at 11:46
"array_key_exists can surely do the trick." that is the answer..good.. +1 for u – Dipesh Parmar Mar 9 at 11:46
You should answer this question and then mark it as solved. Otherwise it'll always look like an open question. – Colin Morelli Mar 9 at 11:57
Can't accept my own answer before two days ^^ – Virus721 Mar 9 at 12:04

This is the very good question and you can use get_defined_vars() for this:

$foo = NULL;
$a = get_defined_vars();

if (array_key_exists('def', $a)) {
   // Should evaluate to FALSE
 }; 

if (array_key_exists('foo', $a)) {
   // Should evaluate to TRUE
};

This will solve your problem

share|improve this answer
Ok but add the array_key_exist thing in it then – Virus721 Mar 9 at 12:20
up vote 2 down vote accepted

The function array_key_exists() can do that, and property_exists() for objects, plus what Vineet1982 said. Thanks for your help.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.