了解如何检查键是否存在,如果存在,则从php中的数组中获取该键的值。
例如
我有这个阵列:
$things = array(
'AA' => 'American history',
'AB' => 'American cooking'
);
$key_to_check = 'AB';
现在,我需要检查$key_to_check是否存在,如果存在,则获取相应的值,在这种情况下,该值将是美式烹饪
if(isset($things[$key_to_check])){
echo $things[$key_to_check];
}
我知道这个问题很老了,但对于那些来这里的人来说,知道在php7中可以使用Null凝聚算子可能会很有用
if ($value = $things[ $key_to_check ] ?? null) {
//Your code here
}
if (array_key_exists($key_to_check, $things)) {
return $things[$key_to_check];
}
isset()将返回:
-true if the key exists and the value is != NULL
-false if the key exists and value == NULL
-false if the key does not exist
array_key_exists()将返回:
-true if the key exists
-false if the key does not exist
因此,如果您的值可能为NULL,那么正确的方法是array_key_exists
。如果您的应用程序不区分NULL和无键,两者都可以,但array_key_exists
总是提供更多选项。
在下面的示例中,数组中没有键返回NULL,但给定键的值为NULL也是如此。这意味着它实际上与isset
相同。
null联合运算符(??)直到PHP 7才添加,但这可以追溯到PHP 5,可能是4:
$value = (array_key_exists($key_to_check, $things) ? $things[$key_to_check] : NULL);
作为一个函数:
function get_from_array($key_to_check, $things)
return (array_key_exists($key_to_check,$things) ? $things[$key_to_check] : NULL);
最简单的方法是这样做:
if( isset( $things[ $key_to_check ]) ) {
$value = $things[ $key_to_check ];
echo "key {$key_to_check} exists. Value: {$value}";
} else {
echo "no key {$key_to_check} in array";
}
你可以通过通常的方式获得价值:
$value = $things[ $key_to_check ];
只需使用isset()
,如果您想将其用作函数,可以按如下方式使用:
function get_val($key_to_check, $array){
if(isset($array[$key_to_check])) {
return $array[$key_to_check]);
}
}
对于Laravel用户,您可以开箱即用,这要归功于照明/支持库:
// use IlluminateSupportArr;
Arr::get($array, $key, $default_value)
相当于:
array_key_exists($key, $array) ? $array[$key] : $default_value;
此助手支持键的点表示法。例如:"key1.key2.key3"
,相当于做$array["key1"]["key2"]["key3"]
。
在Laravel(例如vanillaPHP)之外,您可以使用composer手动添加此库。
试试这个:
$value = @$things[$key_to_check] ?? $default_value;