34

How can I check if a key exists? If yes, then how do I 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 corresponding value, which in this case will be American cooking.

3
  • 1
    What have you tried? Commented Sep 4, 2012 at 17:34
  • Matt I have tried 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. Commented Sep 4, 2012 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'); laravel.com/docs/5.1/helpers#method-array-get Commented Mar 25, 2016 at 18:51

7 Answers 7

54
if(isset($things[$key_to_check])){
    echo $things[$key_to_check];
}
Sign up to request clarification or add additional context in comments.

3 Comments

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?
@Mihai Iorga thanks a lot, very simpel but time saving snippet
It isn't a given that this is slower from the PHP interpreter usage itself. It's very much possible that the interpreter optimises the code internally no matter what variant is being used,. The worst code here is in any case the Laravel version, if the interpreter does not expand these little helper function. Also it's a simple matter of the overall design if isset or the array_key_exiss is the proper answer, as can be seen if we're using filter_input_array(). That can be configured how to return data. Benchmarks are needed to determine what is best.
45

It might be useful to know that in PHP 7, you can use the null coalescing operator:

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

2 Comments

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.
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 nulls in array, have to use array_key_exists as seen in other answers.)
36
if (array_key_exists($key_to_check, $things)) {
    return $things[$key_to_check];
}

3 Comments

If he doesn't know how to get a value based on a key you expect to understand what you meant?
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.
This is more correct than the accepted answer, as isset would return false if the value is null even though the key actually exists
5

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);

Comments

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 the usual way:

$value = $things[ $key_to_check ];

1 Comment

and how are you supposed to return the corresponding value?
1

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.

Comments

1

Just use isset(). You can use it as follows if you want to use it as a function:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.