Friday, 12 April 2013

isset() or array_key_exists() ?


Firstly I wanted to say I'm sorry for not posting much recently, unfortunately they've been a few personal emergencies which have come up recently so I've not been able to get anything written.

Recently a work colleague asked a really good question, what the difference between isset() and array_key_exists() when seeing if a specific key exists inside an array?

The answer

Well the main difference is that isset() returns false if the array key exists but the value is NULL where as array_key_exists() will return true.

The other difference is that isset() seems to be faster, I've put a link below to a comment on the PHP manual which states this and there are other posts on the Internet if you Google it but I've not tested it out myself.

What do I think?

If you know for certain that they array key will not have the value NULL then use isset() as it's quicker but it's only slightly quicker so if you're not certain then use array_key_exists() as it's far better lose that tiny bit of speed (probably unnoticeable in most cases) rather than get a false positive.

Further reading

No comments:

Post a Comment