Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a PHP variable exists, even if its value is NULL?

Tags:

php

null

isset

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

like image 495
FMaz008 Avatar asked Oct 06 '11 12:10

FMaz008


People also ask

How check variable is NULL in PHP?

To check if the variable is NULL, use the PHP is_null() function. The is_null() function is used to test whether the variable is NULL or not. The is_null() function returns TRUE if the variable is null, FALSE otherwise. There is only one value of type NULL, and it is the case-insensitive constant NULL.

How do you check if a variable is undefined in PHP?

You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL.

Does Isset check for NULL?

Definition and Usage The isset() function determines whether a variable is set. To be considered a set, it should not be NULL. Thus, the isset() function also checks whether a declared variable, array or array key has a null value. It returns TRUE when the variable exists and is not NULL; else, it returns FALSE.


2 Answers

Use the following:

$a = NULL;
var_dump(true === array_key_exists('a', get_defined_vars()));
like image 94
Dmytro Shevchenko Avatar answered Sep 27 '22 21:09

Dmytro Shevchenko


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
}
like image 44
Paul Dixon Avatar answered Sep 27 '22 20:09

Paul Dixon