phparraysarray-key-exists

Is it safe not to use array_key_exists() when checking if an item is in the array?


I know it's possible in PHP to check if the item is in the array this way:

if( my_array['item_one'] ){ # some code here... }

That's because if the item isn't, then null value (that equals to false or zero) is returned instead.

But will it always work? Will it always be safe to do it this way (because you know... PHP)?


Solution

  • This idiom is a bad idea. First, as noted in the comments, attempting to access a non-existent value in an array will generate an unknown index error. Second, and more important, 0 and FALSE are most definitely real values, but evaluating keys that point to such values with a snippet like you suggest will act as though they aren't there, which is just plain wrong.

    To make a long story short - PHP has an excellent tool to check if an array contains a key - array_key_exists. There's no reason not to use it.