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'];
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'];
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"
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.