Is it possible to declare an array as constant [duplicate]

We can define a constant like

define("aconstant','avalue');

Can't we define array in this fashion like below ?

define("months",array("January", "February", ---); 

you can use const for that purpose since PHP 5.6 (via nikic).

const months = ["January", "February"];
var_dump("January" === months[0]);

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.


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

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.