0

Possible Duplicate:
Check if value isset and null

If I have $v = NULL; how can I check that $v is exists and it's NULL?

isset($v) => false //because of NULL, but $v exists
Community
  • 1
  • 1
Yekver
  • 4,985
  • 7
  • 32
  • 49

4 Answers4

5

You can’t, null is equivalent to a non-existing variable:

A variable is considered to be null if:

  • it has been assigned the constant NULL.
  • it has not been set to any value yet.
  • it has been unset().

Only for arrays you can check whether a key exists although its value is null using array_key_exists.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • +1 This answer is more correct than the others because it addresses both parts of the question ($v exists AND is null). – George Cummins Mar 14 '12 at 19:53
  • Erm, what's about using `array_key_exists` with `$GLOBALS`? http://www.php.net/manual/en/reserved.variables.globals.php – kirilloid Mar 14 '12 at 20:05
  • @kirilloid That would work – but only with [global variables](http://php.net/language.variables.scope). – Gumbo Mar 14 '12 at 21:40
  • I know, this is similar to JS. You cannot access global variable by its name with `window[name]`, but it's impossbile for variables in current scope. – kirilloid Mar 14 '12 at 21:44
  • -1 You CAN. Based on my answer [here](http://stackoverflow.com/questions/3803282/check-if-value-isset-and-null#answer-39721756), to check that $v exists and it's NULL you would do: `array_key_exists('v', compact('v')) && is_null($v);` – nzn Jan 17 '17 at 10:00
0

Try is_null($v).

The PHP online docs are friendly!

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

You should be careful using isset on variables that can be null. It's a good way to set yourself up for bugs and problems in the future.

What you could do for now is to use is_null as an additional test.

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
-1

If you would like to put it all together to test existence and a null value

<?php
if(!is_null($v)){
// do something
}
?>
Tim Wickstrom
  • 5,476
  • 3
  • 25
  • 33