56

We can define a constant like

define("aconstant','avalue');

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

define("months",array("January", "February", ---); 
NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
mrN
  • 3,734
  • 15
  • 58
  • 82
  • 3
    You can somewhat convert an array to a string and store it as a constant. When you need it, you just reconvert it. Look into the (un)serialize example: http://stackoverflow.com/questions/1290318/php-constants-containing-arrays – Armfoot Jun 27 '13 at 07:59
  • 2
    Yes, from PHP 5.6 on you can do this. See http://stackoverflow.com/a/26470982/1163786 – Jens A. Koch Jan 03 '15 at 20:53

7 Answers7

80

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

const months = ["January", "February"];
var_dump("January" === months[0]);
masakielastic
  • 4,540
  • 1
  • 39
  • 42
  • @cHao: Good one! ^^ Still, I love that it is possible in 5.6, and this de facto is the cleanest/perfect answer for 5.6 onwards. Even with 5.3 still being mainly used and 5.6 running on less than 1% of all php websites, this deserves more than 1 upvote, just for pointing out the existence of that feature (and so that many years from now, when those versions are more standard, this doesn't sit at 1 upvote, while the recommendation to use a variable has over 200 upvotes + accepted). Sry the rant, I actually really like your comment! ^^ – Levite Dec 11 '14 at 07:27
  • To clarify, this is only possible within a class? – Jay Sheth Jul 13 '16 at 18:25
61

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.

André Chalella
  • 13,788
  • 10
  • 54
  • 62
Dejan Marjanović
  • 19,244
  • 7
  • 52
  • 66
  • 2
    Just in case anyone doesn't notice the other answer, you can create a "const" array in PHP 5.6 or newer. – orrd Sep 05 '15 at 06:52
  • 1
    Isn't `$months = array("January,"February",...)` missing a quotation mark? – Callan Heard Dec 04 '15 at 22:26
  • 2
    Just to be clear, the PHP 7 introduction includes associative arrays too. `define('MY_ANIMALS', array('dog' => 'Ottie', 'cat' => 'Garfield', 'bird'=>'Tweetie')); echo MY_ANIMALS['cat']; //outputs 'Garfield' ` – owenmck Dec 10 '15 at 12:22
  • Pre 7: `define('ANIMALS', json_encode( array('dog', 'cat', 'bird') ) );` Then when referencing: `json_decode(ANIMALS, true);` Slightly inconvenient, but sometimes (like if you're storing the structure of your DB(s) for smarter querying inside a framework) it is much more worth it to do it this way than to make a call to the DB unnecessarily. – Nate I Mar 15 '16 at 23:51
  • 1
    The same applies to to class constants in PHP 7. – Andreas Nov 10 '16 at 03:31
29

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);
Sim
  • 2,627
  • 1
  • 20
  • 21
  • 3
    +1, but I wonder , what about json_encode and json_decode? which one is better for memory and performance? – jeff Feb 11 '14 at 16:56
  • 4
    @CengizFrostclaw: `serialize` would be better in most cases. Even if it ended up being a little slower (which i'd guess is the opposite of the truth), it natively supports PHP concepts like references and typed objects, which would not survive a round trip through JSON. – cHao Mar 11 '14 at 12:49
  • @cHao, yes serialize is faster, but it's also dangerous as it might execute code. Even if here this doesn't apply, I think a security aware developer should get used to using the least dangerous methods. In this case, the performance difference is negligible and I think the JSON methods are better here. – Mario Awad Dec 08 '14 at 13:23
  • 1
    @MarioAwad: In this case, security is not an issue -- constants are defined by the programmer, not the user. I wouldn't `unserialize($input)`, but i certainly wouldn't be worried about a string that i wrote and that by definition won't have been tampered with. – cHao Dec 08 '14 at 14:27
  • @cHao you're definitely right and I already stated that here in this case this doesn't apply. Still, I think we should get used to using the least dangerous methods. – Mario Awad Dec 08 '14 at 15:05
  • 2
    @MarioAwad: We shouldn't get used to blindly using the "least dangerous" methods; that way lies cargo cultism. We should get used to *evaluating the dangers*. Frankly, for purely internal stuff, the security risks associated with user input simply don't exist. The greater danger is that what you get out might not be what you put in, and JSON can be pretty bad about that sometimes. (Try `json_encode`ing anything that refers back to itself.) I'll grant that `explode` would be simpler in this case. But JSON is overkill (and codewise, allows for unintended data structures to be passed in). – cHao Dec 08 '14 at 17:38
  • @cHao thank you for the clarifications and excellent points. I'm sure this discussion will be helpful as a future reference. Cheers. – Mario Awad Dec 08 '14 at 17:55
  • @halilpazarlama http://tinyurl.com/serializespeed It would appear json_encode is much faster. Found: http://www.niden.net/2011/11/fast-serialization-of-data-in-php-how.html – ChristoKiwi Apr 13 '15 at 00:41
11

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.

Ilia Ross
  • 13,086
  • 11
  • 53
  • 88
Dennis Haarbrink
  • 3,738
  • 1
  • 27
  • 54
  • 1
    +1 I wonder why PHP allows defining constant resources in the first place? – BoltClock Sep 27 '10 at 11:56
  • @BoltClock's a Unicorn: I don't know exactly, have never come across the explanation. But given the development history of php it wouldn't surprise it is because of some 'historic reasons'.. :) – Dennis Haarbrink Sep 27 '10 at 12:06
9

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);
Exit196
  • 308
  • 3
  • 6
6

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

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.

jfmercer
  • 3,641
  • 3
  • 29
  • 35