DEV Community

Joël Harkes
Joël Harkes

Posted on

Stop using isset() in PHP - Try This Instead!

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';
}
Enter fullscreen mode Exit fullscreen mode

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';
}
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
manuelcanga profile image
Manuel Canga

In ancient times, array_key_exists was slower than isset. For this reason, many of us used to use isset most of time.
Currently, array_key_exists is equal, or more, fast than isset if you use FQN. I mean, you should to write: \array_key_exists and not array_key_exists.

More information in: github.com/php/php-src/pull/3360