我有以下数组:
$a = array('a' => 1,'b' => 2,'c' => null);
我想找到一种方法来访问给定键的元素值,如果键不存在,则为假值。
通过上面的例子,我想$a['d']
给我一个假值。(类似于JavaScript:({}).b // -> undefined
(。
我该怎么做?
编辑:在我的特定情况下,我不在乎例如$a['c'] => false
.
在 PHP 7.0 及更高版本中,您可以使用空合并运算符:
$d = $a['d'] ?? false;
在 PHP 5.3 及更高版本中,您可以使用三元语句:
$d = isset($a['d']) ? $a['d'] : false;
下面在 PHP7.0.20 中测试
PHP 脚本
$a = array('a' => 1,'b' => 2,'c' => 3);
$b1 = $a['b'] ?? false;
$b2 = isset($a['b']) ? $a['b'] : false;
$b3 = $a['b'] ?: false;
$d1 = $a['d'] ?? false;
$d2 = isset($a['d']) ? $a['d'] : false;
// Undefined Error
// $d3 = $a['d'] ?: false;
var_dump([
'b1' => $b1,
'b2' => $b2,
'b3' => $b3,
'd1' => $d1,
'd2' => $d2,
// 'd3' => $d3
]);
控制台输出
| => php test.php
array(5) {
["b1"]=>int(2)
["b2"]=>int(2)
["b3"]=>int(2)
["d1"]=>bool(false)
["d2"]=>bool(false)
}
有关参考,请参阅:
- http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
- http://php.net/manual/de/migration70.new-features.php#migration70.new-features.null-coalesce-op(
也许你应该尝试一下:
echo empty($a['d'])?false:$a['d'];
有一个函数...
唯一正确的方法
$my_array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => null);
if(array_key_exists('d', $my_array)){
// Do something
}
else{
// Do something else
}
另外,要特别注意'd' => null
因为数据库很乐意返回null
值
// The almost right way
$my_array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => null);
$result = array_key_exists( 'd', $my_array ) ? $my_array['d'] : false;
var_dump( $result );
// The wrong way
$result = isset($my_array['d']) ? $my_array['d'] : false;
var_dump( $result );
我发布了"几乎正确的方式",因为该值实际上可以是一个false
,见下文:
$my_array = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => false);
// $result it going to be false but there is no way to tell if this is due to the key being missing or if the key's value is literally false
$result = array_key_exists( 'd', $my_array ) ? $my_array['d'] : false;
如果发生上述情况,则所有逻辑都将消失。