3

Is there a possibility to make a group of constants and get them exactly like an array instead of writing each constant independently ?

something like

echo MYCONST[0]; or 
echo MYCONST['name'];
1
  • Of course it is possible Commented May 1, 2017 at 10:01

2 Answers 2

10

What you are looking for is called Constant array :

it is now possible to do this with define() but only for PHP7 . However you can do this on PHP5.6 by using the const keyword and it is not possible to perform this in lower PHP versions

here is an example :

<?php

define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);

echo ANIMALS[1]; // outputs "cat"

define('MYCONST', [
    'key' => "value"

    ]);

echo MYCONST['key']; // outputs "value"
Sign up to request clarification or add additional context in comments.

Comments

9

1. If you are using PHP7 , you can define a constant as an array.

define('MYCONST', array("someValue1","someValue2"));

2. Version below PHP7 , you can store a string as a constant, whether it can be JSON string or serialized string.

define('MYCONST', json_encode(array("someValue1","someValue2")));
define('MYCONST', serialize(array("someValue1","someValue2")));

For accessing the constant in version below PHP7 (If it is JSON or serialized string), you must json_decode or unserialize respectively.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.