8
$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?

TRiG
  • 10,148
  • 7
  • 57
  • 107
FMaz008
  • 11,161
  • 19
  • 68
  • 100
  • 4
    Why? Just initialize your variables properly and you _know_ which one exists and which doesn't – KingCrunch Oct 06 '11 at 12:52
  • I wouldn't even use isset. Initialize your variables so you can assume they exist. – GolezTrol Oct 06 '11 at 12:57
  • 2
    http://stackoverflow.com/questions/418066/best-way-to-test-for-a-variables-existence-in-php-isset-is-clearly-broken – aziz punjani Oct 06 '11 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. – FMaz008 Oct 06 '11 at 13:05
  • @Insterstellar_Coder: Thanks, I had not found that topic :) ( Even if I don't really like the _GLOBAL solution ) – FMaz008 Oct 06 '11 at 13:08

2 Answers2

9

Use the following:

$a = NULL;
var_dump(true === array_key_exists('a', get_defined_vars()));
Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
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
}
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348