Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array value isset and is null

How to check if array variable

$a = array('a'=>1, 'c'=>null);

is set and is null.

function check($array, $key)
{
    if (isset($array[$key])) {
        if (is_null($array[$key])) {
            echo $key . ' is null';
        }
        echo $key . ' is set';
    }
}

check($a, 'a');
check($a, 'b');
check($a, 'c');

Is it possible in PHP to have function which will check if $a['c'] is null and if $a['b'] exist without "PHP Notice: ..." errors?

like image 756
Bartek Kosa Avatar asked Jul 20 '13 21:07

Bartek Kosa


1 Answers

Use array_key_exists() instead of isset(), because isset() will return false if the variable is null, whereas array_key_exists() just checks if the key exists in the array:

function check($array, $key)
{
    if(array_key_exists($key, $array)) {
        if (is_null($array[$key])) {
            echo $key . ' is null';
        } else {
            echo $key . ' is set';
        }
    }
}
like image 159
nickb Avatar answered Oct 15 '22 04:10

nickb