Home    Articles


How to define a constant that contains an array in PHP


In order to define a constant with an array as value you need to know that the constants cannot change during the code flow, also this regular expresion [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]* is telling you that the constants name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

Constants are only strings. There are two ways to use constants with array as values.

1) First way to declare a CONSTANT

..the value of the constant is an serialized array (string)

# define the constant, the value is an serialized array.
define ('CARS', serialize(array("bmw", "chevrolet", "mercedes")));
# how to use it
$my_fruits = unserialize (CARS);

2) The second way to declare a CONSTANT

…use a class and declare the constants there (this is not a way where real constants are used). It is an alternative.

class Constants 
    public static $cars= array("bmw", "chevrolet", "mercedes");
# update "constant" value
Constants::$cars[] = 'newValue';
# echo it
echo Constants::$cars;

Let us know if this helped you.