不要忘记函数 isset() 不会为对应于 NULL 值的数组键返回 TRUE,而 array_key_exists() 会。所以以上所有答案都不能正确处理数组中的 NULL 元素。对于这种情况,您可以查看我的编辑答案。例如我们有一些数组:
$test = array(NULL,'',0,false,'0');
如果我们使用(来自本主题上面的答案)函数:
function ifsetor(&$value, $default = null) {
return isset($value) ? $value : $default;
}
并尝试获取数组数据:
echo '---------------------';
var_dump($test);
echo 'Array count : '.count($test).'<br>';
echo '---------------------';
var_dump(ifsetor($test[0], 'Key not exists'));
var_dump(ifsetor($test[1],'Key not exists'));
var_dump(ifsetor($test[2],'Key not exists'));
var_dump(ifsetor($test[3], 'Key not exists'));
var_dump(ifsetor($test[4],'Key not exists'));
var_dump(ifsetor($test1[5],'Key not exists'));
function ifsetor(&$value, $default = null) {
return isset($value) ? $value : $default;
}
我们的结果是:
---------------------
array (size=5)
0 => null
1 => string '' (length=0)
2 => int 0
3 => boolean false
4 => string '0' (length=1)
Array count : 5
---------------------
string 'Key not exists' (length=9) //But value in this key of array - NULL! and key exists
string '' (length=0)
int 0
boolean false
string '0' (length=1)
string 'Key not exists' (length=9)
所以我们可以一起使用 isset 和 array_key_exists 来检查它。不要忘记检查这是不是数组;
echo '---------------------';
var_dump($test);
echo 'Array count : '.count($test).'<br>';
echo '---------------------';
var_dump(array_get($test, 0, 'Key not exists'));
var_dump(array_get($test, 1,'Key not exists'));
var_dump(array_get($test, 2,'Key not exists'));
var_dump(array_get($test, 3, 'Key not exists'));
var_dump(array_get($test, 4,'Key not exists'));
var_dump(array_get($test, 5,'Key not exists')); //Key not exists
var_dump(array_get($test1, 5,'Key not exists')); //This is not array
function array_get($arr, $key, $default=null) {
if(is_array($arr)){
return isset($arr[$key]) || array_key_exists($key, $arr)
? $arr[$key]
: $default;
}else{
return 'No array given';
}
}
现在答案是正确的:
---------------------
array (size=5)
0 => null
1 => string '' (length=0)
2 => int 0
3 => boolean false
4 => string '0' (length=1)
Array count : 5
---------------------
null //Perfect - key exists!
string '' (length=0)
int 0
boolean false
string '0' (length=1)
string 'No array given' (length=14)
string 'Key not exists' (length=14)