-4

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

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Michal
  • 43
  • 8
  • 7
    You can hardly blame php for sloppy programming... – jeroen Sep 08 '16 at 08:57
  • Thats not valid PHP and NO Its not safe as if the occurance does not exist it will generate an `unknown index error` – RiggsFolly Sep 08 '16 at 09:00
  • 1
    You can use `isset($my_array['item_one'])` if `array_key_exists()` is to long a function name for you – RiggsFolly Sep 08 '16 at 09:01
  • Oh boy, guys with '(because you know... PHP)' I just wanted to point out that in PHP there can always be something what doesn't have to be obvious to you at first glance. After all that's why I'm rather asking this question! – Michal Sep 08 '16 at 09:05
  • 1
    You are mistaken. It is not possible to check if the item is in the array in the way you're describing. `array_key_exists` is the correct way to check if the item is in the array, and `isset` is the correct way to check if the item is in the array and not null. – apokryfos Sep 08 '16 at 09:12
  • nest it on a try catch if what you want is to don't take advantage of the language you are using – Carlos Fdev Sep 08 '16 at 09:22

1 Answers1

4

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • To be exact PHP throws: `Notice: Undefined index: item_one in /Applications/MAMP/htdocs/exp/main.php on line 21`, so If I understand it properly you mean that this notice could make some troubles in the future? – Michal Sep 08 '16 at 09:16
  • I'm not an expert, but after some time of thinking it become clear to me that for many reasons it's good to know that your code can't accidentally stray from the path when it is in the production. Therefore `array_key_exists()` is realy the proper way for PHP. Whether `isset()` is also sufficient enought, that's a different discussion. – Michal Sep 08 '16 at 09:38