Search code examples
phparraysconstantsdefinedphp-7

How to check does array key exist in defined constant array [PHP 7 define()]


PHP7 brought possibility define array constants with define(). In PHP 5.6, they could only be defined with const.

So I can use define( string $name , mixed $value )) to set array of constants, but it seems that it forgot to bring also upgrade of defined ( mixed $name ) along since it still only accepts string value or am I missing something?

PHP v: < 7 I had to define every animal separately define('ANIMAL_DOG', 'black');, define('ANIMAL_CAT', 'white'); etc. or serialize my zoo.

PHP v: >= 7 I can define entire zoo which is freaking awesome, but I can't find my animal in the zoo as simply I can find single ANIMAL. It is reasonable in the real world, but here's supplementary question if I haven't miss something.

Is that intentional that defined(); does not accept array?. If I define my zoo...

define('ANIMALS', array(
    'dog' => 'black',
    'cat' => 'white',
    'bird' => 'brown'
));

... why can't I find my dog simply defined('ANIMALS' => 'dog');?

1. Prints always: The dog was not found

print (defined('ANIMALS[dog]')) ? "1. Go for a walk with the dog\n" : "1. The dog was not found\n";

2. Prints always: The dog was not found and when dog really does not exist shows Notice + Warning

/** if ANIMALS is not defined
  * Notice:  Use of undefined constant ANIMALS - assumed ANIMALS...
  * Warning:  Illegal string offset 'dog'
  * if ANIMALS['dog'] is defined we do not get no warings notices
  * but we still receive The dog was not found */
print (defined(ANIMALS['dog'])) ? "2. Go for a walk with the dog\n" : "2. The dog was not found\n";

3. regardless of whether the ANIMALS, ANIMALS['dog'] is defined or not, I get Warning:

/* Warning:  defined() expects parameter 1 to be string, array given...*/  
print defined(array('ANIMALS' => 'dog')) ? "3. Go for a walk with the dog\n" : "3. The dog was not found\n";

4. I get Notice if ANIMALS['dog'] is not defined

/* Notice: Use of undefined constant ANIMALS - assumed 'ANIMALS' */
print (isset(ANIMALS['dog'])) ? "4. Go for a walk with the dog\n" : "4. The dog was not found\n";

5. So am I correct that there is only one option left then?

print (defined('ANIMALS') && isset(ANIMALS['dog'])) ? "Go for a walk with the dog\n" : "The dog was not found\n";

Solution

  • PHP 7 allows you to define a constant array, but what is being defined as a constant in that case is the array itself, not its individual elements. In every other regard the constant functions as a typical array, so you'll need to use conventional methods to test for the existence of a specific key within it.

    Try this:

    define('ANIMALS', array(
        'dog'  => 'black',
        'cat'  => 'white',
        'bird' => 'brown'
    ));
    
    print (defined('ANIMALS') && array_key_exists('dog', ANIMALS)) ?
        "Go for a walk with the dog\n" : "The dog was not found\n";