2016-09-08 08:55
浏览 48


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)?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqu3974
    dqu3974 2016-09-08 09:06

    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.

    点赞 评论