How to check if array variable
如何检查数组变量
$a = array('a'=>1, 'c'=>null);
is set and is null.
已设置且为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 Notice:...”错误?
2 个解决方案
#1
35
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:
使用array_key_exists()而不是isset(),因为如果变量为null,则isset()将返回false,而array_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';
}
}
}
#2
0
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
但isset将在null值上返回false。您可以尝试使用array_key_exists
#1
35
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:
使用array_key_exists()而不是isset(),因为如果变量为null,则isset()将返回false,而array_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';
}
}
}
#2
0
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
但isset将在null值上返回false。您可以尝试使用array_key_exists