Check if value isset and null

68,569

Solution 1

IIRC, you can use get_defined_vars() for this:

$foo = NULL;
$vars = get_defined_vars();
if (array_key_exists('bar', $vars)) {}; // Should evaluate to FALSE
if (array_key_exists('foo', $vars)) {}; // Should evaluate to TRUE

Solution 2

If you are dealing with object properties which might have a value of NULL you can use: property_exists() instead of isset()

<?php

class myClass {
    public $mine;
    private $xpto;
    static protected $test;

    function test() {
        var_dump(property_exists($this, 'xpto')); //true
    }
}

var_dump(property_exists('myClass', 'mine'));   //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto'));   //true, as of PHP 5.3.0
var_dump(property_exists('myClass', 'bar'));    //false
var_dump(property_exists('myClass', 'test'));   //true, as of PHP 5.3.0
myClass::test();

?>

As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.

Solution 3

See Best way to test for a variable's existence in PHP; isset() is clearly broken

 if( array_key_exists('foo', $GLOBALS) && is_null($foo)) // true & true => true
 if( array_key_exists('bar', $GLOBALS) && is_null($bar)) // false &  => false

Solution 4

I found this topic when I was looking for a solution for an array. to check for the presence of an array element that contains NULL, this construction helped me

    $arr= [];
    $foo = 'foo';
    $arr[$foo]= NULL;
    if (array_key_exists('bar', $arr)) {}; // Should evaluate to FALSE
    if (array_key_exists('foo', $arr)) {}; // Should evaluate to TRUE
    if (array_key_exists($foo, $arr)) {}; // Should evaluate to TRUE

Solution 5

I have found that compact is a function that ignores unset variables but does act on ones set to null, so when you have a large local symbol table I would imagine you can get a more efficient solution over checking array_key_exists('foo', get_defined_vars()) by using array_key_exists('foo', compact('foo')):

$foo = null;
echo isset($foo) ? 'true' : 'false'; // false
echo array_key_exists('foo', compact('foo')) ? 'true' : 'false'; // true
echo isset($bar) ? 'true' : 'false'; // false
echo array_key_exists('bar', compact('bar')) ? 'true' : 'false'; // false

Update

As of PHP 7.3 compact() will give a notice for unset values, so unfortunately this alternative is no longer valid.

compact() now issues an E_NOTICE level error if a given string refers to an unset variable. Formerly, such strings have been silently skipped.

Share:
68,569

Related videos on Youtube

Tatu Ulmanen
Author by

Tatu Ulmanen

Web programmer from Finland.

Updated on January 18, 2022

Comments

  • Tatu Ulmanen
    Tatu Ulmanen over 2 years

    I need to check if value is defined as anything, including null. isset treats null values as undefined and returns false. Take the following as an example:

    $foo = null;
    
    if(isset($foo)) // returns false
    if(isset($bar)) // returns false
    if(isset($foo) || is_null($foo)) // returns true
    if(isset($bar) || is_null($bar)) // returns true, raises a notice
    

    Note that $bar is undefined.

    I need to find a condition that satisfies the following:

    if(something($bar)) // returns false;
    if(something($foo)) // returns true;
    

    Any ideas?

    • max4ever
      max4ever almost 12 years
      if(isset($foo)) // returns false, i fell off the chair, all these years...
    • Jack
      Jack over 5 years
      in_array($key,array_keys($_SESSION)) && is_null($_SESSION[$key]) I was wondering this for so long ..
    • Vincent Decaux
      Vincent Decaux almost 5 years
      This is not a normal behave for me, isset = is set ?, your variable is set at null. I wasted lot of time because of this one...
    • Sebi2020
      Sebi2020 almost 3 years
      @VincentDecaux it's PHP... Just an example of many more illogical things in the language...
  • Tatu Ulmanen
    Tatu Ulmanen almost 14 years
    I am using is_null. The result is same regardless of the isset.
  • Raveline
    Raveline almost 14 years
    I made a mistake while posting my first answer : did you try with empty() ?
  • Loïc Février
    Loïc Février almost 14 years
    No, he said that if(isset($bar)) gives false when $bar = null.
  • Raveline
    Raveline almost 14 years
    The code you quote only works if the variable is in the global scope.
  • Loïc Février
    Loïc Février almost 14 years
    Indeed but isn't it the most frequent case ? In a function you will have variables at global scope and arguments (which are always defined). You could also have object properties but then you can use 'property_exists'.
  • salathe
    salathe almost 14 years
    +1 I was going to suggest the same function, get_defined_vars happily copes with scope.
  • Tatu Ulmanen
    Tatu Ulmanen almost 14 years
    This will not pass any other variables than null (eg. if $bar = "test").
  • Tatu Ulmanen
    Tatu Ulmanen almost 14 years
    Doesn't look very portable.. :)
  • Tatu Ulmanen
    Tatu Ulmanen almost 14 years
    Seems to be working, but I was hoping for something simpler. Oh well. Let's see if anyone can come up with a one liner.
  • Tatu Ulmanen
    Tatu Ulmanen almost 14 years
    Using $GLOBALS seems a bit volatile, I have to do some testing myself before I can declare this as working.
  • Hannes
    Hannes almost 14 years
    well, you don't need vars, so in theory its one line "if(array_key_exists('foo',get_defined_vars())){} "
  • Bartek Kosa
    Bartek Kosa almost 11 years
    When $bar = null isset() will return "false" and is_null() will return true. False and true gives always false.
  • Teaqu
    Teaqu over 10 years
    This won't work for values that are not empty and not NULL such as FALSE, 0, array() or "".
  • Teaqu
    Teaqu over 10 years
    You can do the same for arrays with array_key_exists();
  • ToolmakerSteve
    ToolmakerSteve over 7 years
    This answer is wrong. is_null has the same problem as is_set: it can't distinguish between "not set" and "set to null", which is the problem OP has. empty is even worse, as Calum points out.
  • ToolmakerSteve
    ToolmakerSteve over 7 years
    This answer is completely wrong. As OP said, isset($bar) returns false, even after $bar = null;.
  • ToolmakerSteve
    ToolmakerSteve over 7 years
    Interesting alternative. But note that it is probably slower than calling array_key_exists on an existing array, such as $GLOBALS - because a look up in a hash table does not get any slower, when the table gets large, and you've added the extra work of compact. Nevertheless, I upvoted it because it is useful in one situation: if you want to know whether foo exists in the current context, regardless of where it came from - if you don't care whether is local or global, just want to know whether it exists.
  • ToolmakerSteve
    ToolmakerSteve over 7 years
    fvn's newer answer might be a quicker way to get a variable that exists in current context, avoiding the cost of get_defined_vars(): array_key_exists('foo', compact('foo')). Or faster, if testing a global: array_key_exists('foo', $GLOBALS).
  • nzn
    nzn over 7 years
    @ToolmakerSteve - I was actually referring to the potentially significant overhead of calling get_defined_vars. See here.