Is it possible to declare an array as constant
PhpPhp Problem Overview
We can define a constant like
define("aconstant','avalue');
Can't we define array in this fashion like below ?
define("months",array("January", "February", ---);
Php Solutions
Solution 1 - Php
you can use const for that purpose since PHP 5.6 (via nikic).
const months = ["January", "February"];
var_dump("January" === months[0]);
Solution 2 - Php
UPDATE: this is possible in PHP 7 (reference)
// Works as of PHP 7
define('ANIMALS', array(
'dog',
'cat',
'bird'
));
echo ANIMALS[1]; // outputs "cat"
ORIGINAL ANSWER
From php.net...
> The value of the constant; only scalar and null values are > allowed. Scalar values are integer, float, string or boolean values. > It is possible to define resource constants, however it is not > recommended and may cause unpredictable behavior.
$months = array("January,"February",...)
will be just fine.
Solution 3 - Php
You can put arrays inside constants with a hack:
define('MONTHS', serialize(array('January', 'February' ...)));
But then you have to unserialize()
that constant value when needed and I guess this isn't really that useful.
As an alternative, define multiple constants:
define('MONTH_1', 'January');
define('MONTH_2', 'February');
...
And use constant()
function to look up the value:
echo constant('MONTH_'.$month);
Solution 4 - Php
No, you can't. See PHP: Syntax - Manual
> Only scalar data (boolean, integer, float and string) can be contained in constants. > It is possible to define constants as a resource, but it should be avoided, > as it can cause unexpected results.
Solution 5 - Php
You can use JSON format to keep array in string and then assign this string to constant.
$months = array("January","February","March");
define('MONTHS', json_encode($months));
When you want to use it:
$months = json_decode(MONTHS);
Solution 6 - Php
If you must have a constant, how about using a a delimited string and exploding into an array?
define("MONTHS", "January;February;March");
$months = explode(";",MONTHS);
Solution 7 - Php
As of PHP 5.6, it is possible to declare constant arrays. The linked documentation uses the example const ARR = ['a', 'b'];
. You could also do const ARR = array('a', 'b');
. However, in 5.6 there is an odd quirk: you can declare constant arrays using const
, but not define()
. This has been corrected in PHP 7.0.