9
$a = NULL;
$c = 1;
var_dump(isset($a)); // bool(false)
var_dump(isset($b)); // bool(false)
var_dump(isset($c)); // bool(true)

How can I distinguish $a, which exists but has a value of NULL, from the “really non-existent” $b?

5
  • 4
    Why? Just initialize your variables properly and you know which one exists and which doesn't Commented Oct 6, 2011 at 12:52
  • I wouldn't even use isset. Initialize your variables so you can assume they exist. Commented Oct 6, 2011 at 12:57
  • 2
    stackoverflow.com/questions/418066/… Commented Oct 6, 2011 at 13:01
  • 8
    @KingCrunch: Theorical question or specific edge case, either ways the question was not about if it's appropriate or not. Please stay constructive. Commented Oct 6, 2011 at 13:05
  • @Insterstellar_Coder: Thanks, I had not found that topic :) ( Even if I don't really like the _GLOBAL solution ) Commented Oct 6, 2011 at 13:08

2 Answers 2

11

Use the following:

$a = NULL;
var_dump(true === array_key_exists('a', get_defined_vars()));
Sign up to request clarification or add additional context in comments.

Comments

5

It would be interesting to know why you want to do this, but in any event, it is possible:

Use get_defined_vars, which will contain an entry for defined variables in the current scope, including those with NULL values. Here's an example of its use

function test()
{
    $a=1;
    $b=null;

    //what is defined in the current scope?
    $defined= get_defined_vars();

    //take a look...
    var_dump($defined);

    //here's how you could test for $b
    $is_b_defined = array_key_exists('b', $defined);
}

test();

This displays

array(2) {
  ["a"] => int(1)
  ["b"] => NULL
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.