If you're a PHP developer, chances are that you've come across the isset()
function. It's a handy little function that checks whether a variable is set and not null. However, there's another function that you should consider using instead: array_key_exists()
.
So why should you use array_key_exists()
instead of isset()
? The answer is simple: isset()
also returns false even though the variable is set to NULL and won't throw an exception. This can cause unexpected behavior in your code and make it harder to debug.
Let's take a look at an example to illustrate this. Consider the following code:
$data = array(
'foo' => null,
'bar' => 'baz'
);
if (isset($data['foo'])) {
echo 'foo is set';
} else {
echo 'foo is not set';
}
You might expect this code to output "foo is not set" because $data['foo']
is set to null
. However, it actually outputs "foo is set". This is because isset()
returns false when a variable is set to null
.
Now let's rewrite this code using array_key_exists()
:
$data = array(
'foo' => null,
'bar' => 'baz'
);
if (array_key_exists('foo', $data)) {
echo 'foo is set';
} else {
echo 'foo is not set';
}
This code correctly outputs "foo is set". array_key_exists()
checks whether the specified key exists in the array, regardless of whether its value is null
.
Using array_key_exists()
instead of isset()
can also make your code more readable. If you're checking whether a key exists in an array, it's clearer to use a function that's specifically designed for that purpose.
In conclusion, array_key_exists()
is a more reliable and readable way to check whether a key exists in an array than isset()
. Remember that isset()
returns false even if a variable is set to null
, which can cause unexpected behavior in your code. By using array_key_exists()
, you can avoid this issue and make your code more readable at the same time.
Top comments (1)
In ancient times,
array_key_exists
was slower thanisset
. For this reason, many of us used to useisset
most of time.Currently,
array_key_exists
is equal, or more, fast thanisset
if you use FQN. I mean, you should to write:\array_key_exists
and notarray_key_exists
.More information in: github.com/php/php-src/pull/3360