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
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.
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' ).
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.
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() .
if(isset($things[$key_to_check])){ echo $things[$key_to_check]; }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With