tags:

views:

90

answers:

5

How do the follwing two function calls compare:

isset($a['key'])
array_key_exists('key', $a)
A: 

Literally, both do the same there in your code. But note that isset can be used for any variable whereas array_key_exists is used with arrays only.

Sarfraz
A: 

Function isset() is faster, check http://www.php.net/manual/en/function.array-key-exists.php#82867

Anax
A: 

The two are not exactly the same. I couldn't remember the exact differences, but they are outlined very well in http://stackoverflow.com/questions/700227/whats-quicker-and-better-to-determine-if-an-array-key-exists-in-php.

The common consensus seems to be to use isset whenever possible, because it is a language construct and therefore faster. However, the differences should be outlined above.

TNi
The speed difference between the two should be negligible.
Gordon
I am not as sure in large loops. You might still be right, and I would need to benchmark, but small savings can add up in loops. For most practical uses, the difference is, like you say, negligible.
TNi
+6  A: 

array_key_exists will definitely tell you if a key exists in an array, whereas isset will only return true if the key/variable exists and is not null.

$a = array('key1' => 'フーバー', 'key2' => null);

isset($a['key1']);             // true
array_key_exists('key1', $a);  // true

isset($a['key2']);             // false
array_key_exists('key2', $a);  // true
deceze
I wish I understood chineese :)
Zacky112
@Zacky Japanese. And it just says 'foobar'.
deceze
A: 

The main difference when working on arrays is that array_key_exists returns true when the value is null, while isset will return false when the array value is set to null.

See isset on the PHP documentation site.

Matijs
`isset` returns *false* and not *null*.
Gumbo
Corrected, though of course deceze has the more complete answer by now.
Matijs