tags:

views:

342

answers:

5

Consider these 2 examples

$key = 'jim';

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

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

I'm interested in knowing if either of these are better. I've always used the first, but have seen a lot of people use the second example on this site.

So, which is better? Faster? Clearer intent?

Update

Thanks for the quality answers. I now understand the difference between the 2. A benchmark states that isset() alone is quicker than array_key_exists(). However, if you want the isset() to behave like array_key_exists() it is slower.

+1  A: 

As to "faster": Try it (my money is on array_key_exists(), but I can't try it right now).

As to "clearer in the intent": array_key_exists()

Tomalak
isset() is actually significantly faster if you don't care about the null behavior (see http://www.randombenchmarks.com/?p=29).
Matt Kantor
+1  A: 

there is a difference .. from php.net you'll read:

isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.

A very informal test shows array_key_exists() to be about 2.5 times slower than isset()

Scott Evernden
+11  A: 

isset() is faster, but its not the same as array_key_exists(). isset() will return false if the value is NULL or it doesn't exist, while array_key_exists() will return true if it is NULL and false if it doesn't exist.

Richard Levasseur
+2  A: 

Well, the main difference is that isset() will not return true for array keys that correspond to a null value, while array_key_exists() does.

Running a small benchmark shows that isset() it's faster but it may not be entirely accurate.

CMS
Can you run the benchmark again with the more correct "(isset($array[$i]) || $array[$i] === null)"?
Tomalak
Oh, and would you post an indication how much performance difference the two variants show? Thanks!
Tomalak
Did you consider leaving out the `$arraykeyexists_result[]` lines? That’s irrelevant in this case.
Gumbo
wow, that codepad site is awesome +1 for that, and the good answer
alex
@Tomalak, I ran the example you suggested, and it states that array_key_exists() is faster than isset() with the || operator. http://codepad.org/5qyvS93x
alex
Tomalak: that is not more correct. They have different results, and you should use the correct one for readability.
OIS
A: 

Obviously the second example is clearer in intent, there's no question about it. To figure out what example #1 does, you need to be familiar with PHP's variable initialization idiosyncracies - and then you'll find out that it functions differently for null values, and so on.

As to which is faster - I don't intend to speculate - run either in a tight loop a few hundred thousand times on your PHP version and you'll find out :)

Mihai Limbășan