What is a faster and more efficient way to check if a key exists in a PHP array?
P粉512363233
P粉512363233 2023-10-16 08:55:37
0
2
540

Consider these two examples...

$key = 'jim';

// example 1
if (isset($array[$key])) {
    // ...
}

// example 2    
if (array_key_exists($key, $array)) {
    // ...
}

I'm interested to know if these two are better. I've been using the first example, but I've seen a lot of people on this site using the second example.

So, which one is better? hurry up? Clearer intention?

P粉512363233
P粉512363233

reply all(2)
P粉969666670

If you are interested in some of the tests I recently completed:

https://stackoverflow.com/a/21759158/520857

Summary:

| Method Name                              | Run time             | Difference
=========================================================================================
| NonExistant::noCheckingTest()            | 0.86004090309143     | +18491.315775911%
| NonExistant::emptyTest()                 | 0.0046701431274414   | +0.95346080503016%
| NonExistant::isnullTest()                | 0.88424181938171     | +19014.461681183%
| NonExistant::issetTest()                 | 0.0046260356903076   | Fastest
| NonExistant::arrayKeyExistsTest()        | 1.9001779556274      | +209.73055713%
P粉713866425

isset() is faster, but not the same as array_key_exists().

array_key_exists() Purely checks if the key exists, even if the value is NULL.

Given If the key exists and the value is NULL, isset() will return false.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template