php 检查数组值是否已设置并且为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17767094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:23:44  来源:igfitidea点击:

Check if array value isset and is null

phparraysissetisnull

提问by Bartek Kosa

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?

PHP 中是否有可能具有检查 $a['c'] 是否为空以及 $a['b'] 是否存在且没有“PHP 通知:...”错误的函数?

回答by nickb

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

使用array_key_exists()代替isset(), 因为如果变量是isset()则返回,而只检查键是否存在于数组中:falsenullarray_key_exists()

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

回答by RiaD

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 issetwill return falseon null values. You may try array_key_existsinstead

isset会返回false空值。您可以尝试array_key_exists,而不是