Check if array value isset and is null

烂漫一生 提交于 2019-12-21 06:58:46

问题


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?


回答1:


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';
        }
    }
}



回答2:


You may pass it by reference:

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');

SHould give no notice

But isset will return false on null values. You may try array_key_exists instead



来源:https://stackoverflow.com/questions/17767094/check-if-array-value-isset-and-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!