Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a key exists and get a corresponding value from an array in PHP

Tags:

Any idea how to check if a key exists and if yes, then get the value of this key from an array in 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

like image 333
Derfder Avatar asked Sep 04 '12 17:09

Derfder


People also ask

How do you check if a key exists in an array PHP?

PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

How get key from value in array in PHP?

If you have a value and want to find the key, use array_search() like this: $arr = array ('first' => 'a', 'second' => 'b', ); $key = array_search ('a', $arr); $key will now contain the key for value 'a' (that is, 'first' ).

Is used to check if a key element exist in the array?

The array_key_exists() function is used to check whether a specified key is present in an array or not. The function returns TRUE if the given key is set in the array. The key can be any value possible for an array index.

How do you check if value exists in array of objects PHP?

The function in_array() returns true if an item exists in an array. You can also use the function array_search() to get the key of a specific item in an array. In PHP 5.5 and later you can use array_column() in conjunction with array_search() .


2 Answers

if(isset($things[$key_to_check])){     echo $things[$key_to_check]; } 
like image 146
Mihai Iorga Avatar answered Sep 19 '22 16:09

Mihai Iorga


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

if ($value = $things[ $key_to_check ] ?? null) {       //Your code here } 
like image 36
AlTak Avatar answered Sep 17 '22 16:09

AlTak