27

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

Derfder
  • 3,204
  • 11
  • 50
  • 85
  • 1
    [What have you tried](http://www.whathaveyoutried.com)? – Matt Sep 04 '12 at 17:34
  • Matt I have tried http://www.php.net/manual/en/function.array-key-exists.php but I was getting on it too complicated. In fact is very simple. Btw. check flagged comments from me. I have tried 3 times to flag a comment on my previous question from jack, because is really offtopic, without any response from a moderator. Thanks in advance. – Derfder Sep 04 '12 at 17:38
  • If you happen to be using Laravel, they have some nice array helper functions. For example: `array_get($things, $key_to_check, 'optional default value');` https://laravel.com/docs/5.1/helpers#method-array-get – Justin Mar 25 '16 at 18:51

8 Answers8

50
if(isset($things[$key_to_check])){
    echo $things[$key_to_check];
}
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
  • 4
    Isn't it slow because the program first look into the array to check if the key exists, just to look again right after it, to get the value? – TmCrafz Nov 13 '19 at 18:08
  • @Mihai Iorga thanks a lot, very simpel but time saving snippet – Ana DEV May 28 '21 at 11:17
40

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
}
AlTak
  • 449
  • 4
  • 6
  • 2
    nice approach if you are only going to use the value of `$value` if it is set and you do not want to check the array twice. However I'll prefer using `false` instead of `null` as I think it shows better that we will not run the code inside the if statement then. – Oliver Nybroe Mar 26 '19 at 13:52
  • This answer won't execute the code, for any value that is equivalent to boolean false. E.g. for `$value` of `0`, `false`, or empty string. Should do `!== null`. I would write as two lines: `$value = $things[ $key ] ?? null; if ($value !== null) { ... }`. (This assumes `null` is never stored as a value. If do store `null`s in array, have to use `array_key_exists` as seen in other answers.) – ToolmakerSteve Feb 15 '20 at 20:46
29
if (array_key_exists($key_to_check, $things)) {
    return $things[$key_to_check];
}
JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65
  • If he doesn't know how to get a value based on a key you expect to understand what you meant? – Mihai Iorga Sep 04 '12 at 17:29
  • To me, "get" implies he wants to use it for something while print would be echoing and it seemed to me he was more concerned about checking if the key exists than what comes after. – JaredMcAteer Sep 04 '12 at 17:41
  • 11
    This is more correct than the accepted answer, as `isset` would return `false` if the value is `null` even though the key actually exists – Populus Oct 28 '15 at 19:29
3

isset() will return:
-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() will return:
-true if the key exists
-false if the key does not exist

So, if your value may be NULL, the proper way is array_key_exists. If your application doesn't differentiate between NULL and no key, either will work, but array_key_exists always provides more options.

In the following example, no key in the array returns NULL, but so does a value of NULL for a given key. That means it's effectively the same as isset.

The null coalesce operator(??) wasn't added until PHP 7, but this works back to PHP 5, maybe 4:

$value = (array_key_exists($key_to_check, $things) ? $things[$key_to_check] : NULL);

as a function:

function get_from_array($key_to_check, $things)
    return (array_key_exists($key_to_check,$things) ? $things[$key_to_check] : NULL);
Pedro
  • 96
  • 5
2

The simpliest approach is to do this:

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";
}

And you get the value usual way:

$value = $things[ $key_to_check ];
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
0

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

function get_val($key_to_check, $array){
    if(isset($array[$key_to_check])) {
        return $array[$key_to_check]);
    }
}
Sven van Zoelen
  • 6,989
  • 5
  • 37
  • 48
0

For Laravel users, you can use this helper out-of-the-box, thanks to the illuminate/support library:

// use Illuminate\Support\Arr;
Arr::get($array, $key, $default_value)

Which is the equivalent of:

array_key_exists($key, $array) ? $array[$key] : $default_value;

This helper supports the dot notation for keys. Ex: "key1.key2.key3", which is the equivalent of doing $array["key1"]["key2"]["key3"].

Outside Laravel (ex. vanilla PHP), you can manually add this library with composer.

Daniel Loureiro
  • 4,595
  • 34
  • 48
0

Try this:

$value = @$things[$key_to_check] ?? $default_value;
Wajih
  • 4,227
  • 2
  • 25
  • 40