检查密钥是否存在,并从PHP中的数组中获取相应的值

时间:2022-10-26 16:46:19

Any idea how to check if a key exists and if yes, then get the value of this key from an array in php.

知道如何检查密钥是否存在以及是否存在,然后从php中的数组中获取此密钥的值。

E.g.

例如。

I have this array:

我有这个数组:

$things = array(
  'AA' => 'American history',
  'AB' => 'American cooking'
);

$key_to_check = 'AB';

Now, I need to check if $key_to_check exists and if it does, get a coresponding value which in this case will be American cooking

现在,我需要检查$ key_to_check是否存在,如果存在,则获得一个相应的值,在这种情况下将是美国烹饪

5 个解决方案

#1


23  

if(isset($things[$key_to_check])){
    echo $things[$key_to_check];
}

#2


19  

if (array_key_exists($key_to_check, $things)) {
    return $things[$key_to_check];
}

#3


15  

I know this question is very old but for those who will come here It might be useful to know that in php7 you can use Null Coalesce Operator

我知道这个问题很老但是对于那些来到这里的人来说,知道在php7中你可以使用Null Coalesce Operator可能是有用的

if ($value = $things[ $key_to_check ] ?? null) {
      //Your code here
}

#4


1  

The simpliest approach is to do this:

最简单的方法是这样做:

if( isset( $things[ $key_to_check ]) ) {
   $value = $things[ $key_to_check ];
   echo "key exists. Value: ${value}";
} else {
   echo "no such key in array";
}

And you get the value usual way:

而且你得到了通常的价值:

$value = $things[ $key_to_check ];

#5


0  

Just use isset(), you can use it as follows if you want to use it as an function:

只需使用isset(),如果要将其用作函数,可以按如下方式使用:

function get_val($key_to_check, $array){
    if(isset($array[$key_to_check])) {
        return $array[$key_to_check]);
    }
}

#1


23  

if(isset($things[$key_to_check])){
    echo $things[$key_to_check];
}

#2


19  

if (array_key_exists($key_to_check, $things)) {
    return $things[$key_to_check];
}

#3


15  

I know this question is very old but for those who will come here It might be useful to know that in php7 you can use Null Coalesce Operator

我知道这个问题很老但是对于那些来到这里的人来说,知道在php7中你可以使用Null Coalesce Operator可能是有用的

if ($value = $things[ $key_to_check ] ?? null) {
      //Your code here
}

#4


1  

The simpliest approach is to do this:

最简单的方法是这样做:

if( isset( $things[ $key_to_check ]) ) {
   $value = $things[ $key_to_check ];
   echo "key exists. Value: ${value}";
} else {
   echo "no such key in array";
}

And you get the value usual way:

而且你得到了通常的价值:

$value = $things[ $key_to_check ];

#5


0  

Just use isset(), you can use it as follows if you want to use it as an function:

只需使用isset(),如果要将其用作函数,可以按如下方式使用:

function get_val($key_to_check, $array){
    if(isset($array[$key_to_check])) {
        return $array[$key_to_check]);
    }
}