If you want to declare an array as a constant in PHP, you need to look further than what PHP provides as standard. Technically, if you look at PHP's Constants Syntax, it's not possible to define an array as constant, except from PHP 5.6 onwards. As of this writing, PHP 5.6 is still not widely available, and hence here's another quick and simple solution.
To come up with the code below, we looked at many threads on Stack Overflow. This one is the most popular and offers many solutions. The result of our research is this little code snippet below. Keep in mind that we have tried to use the "const" keyword instead of the "define" method presented below and we found out that "const" doesn't work for this trick.
<?php //Define PHP array constant using JSON encode define("FRUITS", json_encode(array( "Watermelon", "Strawberries", "Pomegranate", "Blackberry", ))); //Use array constant in PHP by using JSON decode $fruits = json_decode(FRUITS); var_dump($fruits);
The solution presented in this Stack Overflow post uses PHP's "serialize" and "unserialize" functions to define constant PHP arrays.
We prefer the usage of PHP's JSON encode and decode as they are safer. Let me explain why. Technically, in this context, they are both similar as the input given to "unserialize" is a constant. However, in general, "unserialize" can be used to handle any variable and if given user input the "unserialize" function can be maliciously used to hijack your application or website unless you cleanup the input before passing it to "unserialize". For this reason, we prefer the usage of the safer JSON decode method as it can't be exploited in a similar fashion to "unserialize".
From PHP 5.6 onwards, it is also possible to define an array constant. For example:
<?php const FRUITS = array( "Watermelon", "Strawberries", "Pomegranate", "Blackberry", ); var_dump(FRUITS);
Founder of SOFTKUBE, lead developer, and getting things done addict. Passionate about open source, user interface design, business development, and the tech world.
A small team of experts developing simple, usable, and high-quality web solutions. We blog about business, entrepreneurship, web development, and technology.
Declaring a Constant Array in PHP