PHP Constants Containing Arrays?

329,086

Solution 1

NOTE: while this is the accepted answer, it's worth noting that in PHP 5.6+ you can have const arrays - see Andrea Faulds' answer below.

You can also serialize your array and then put it into the constant:

# define constant, serialize array
define ("FRUITS", serialize (array ("apple", "cherry", "banana")));

# use it
$my_fruits = unserialize (FRUITS);

Solution 2

Since PHP 5.6, you can declare an array constant with const:

<?php
const DEFAULT_ROLES = array('guy', 'development team');

The short syntax works too, as you'd expect:

<?php
const DEFAULT_ROLES = ['guy', 'development team'];

If you have PHP 7, you can finally use define(), just as you had first tried:

<?php
define('DEFAULT_ROLES', array('guy', 'development team'));

Solution 3

You can store them as static variables of a class:

class Constants {
    public static $array = array('guy', 'development team');
}
# Warning: array can be changed lateron, so this is not a real constant value:
Constants::$array[] = 'newValue';

If you don't like the idea that the array can be changed by others, a getter might help:

class Constants {
    private static $array = array('guy', 'development team');
    public static function getArray() {
        return self::$array;
    }
}
$constantArray = Constants::getArray();

EDIT

Since PHP5.4, it is even possible to access array values without the need for intermediate variables, i.e. the following works:

$x = Constants::getArray()['index'];

Solution 4

If you are using PHP 5.6 or above, use Andrea Faulds answer

I am using it like this. I hope, it will help others.

config.php

class app{
    private static $options = array(
        'app_id' => 'hello',
    );
    public static function config($key){
        return self::$options[$key];
    }
}

In file, where I need constants.

require('config.php');
print_r(app::config('app_id'));

Solution 5

This is what I use. It is similar to the example provided by soulmerge, but this way you can get the full array or just a single value in the array.

class Constants {
    private static $array = array(0 => 'apple', 1 => 'orange');

    public static function getArray($index = false) {
        return $index !== false ? self::$array[$index] : self::$array;
    }
}

Use it like this:

Constants::getArray(); // Full array
// OR 
Constants::getArray(1); // Value of 1 which is 'orange'
Share:
329,086
Nick Heiner
Author by

Nick Heiner

JS enthusiast by day, horse mask enthusiast by night. Talks I've Done

Updated on July 08, 2022

Comments

  • Nick Heiner
    Nick Heiner almost 2 years

    This failed:

     define('DEFAULT_ROLES', array('guy', 'development team'));
    

    Apparently, constants can't hold arrays. What is the best way to get around this?

    define('DEFAULT_ROLES', 'guy|development team');
    
    //...
    
    $default = explode('|', DEFAULT_ROLES);
    

    This seems like unnecessary effort.

    • Andrea
      Andrea over 9 years
      PHP 5.6 supports constant arrays, see my answer below.
    • ziGi
      ziGi over 9 years
      When would you need to use an array as a constant, are you trying to do an enumeration? If so, then use SplEnum: php.net/manual/en/class.splenum.php
    • Matt K
      Matt K over 8 years
      @ziGi Came upon this issue today, have different types of images to store that require specific dimensions, it became useful to store these dimensions as constant arrays instead of one for width and one for height.
  • GateKiller
    GateKiller almost 13 years
    Just want to say I love this solution :)
  • Gregoire
    Gregoire almost 13 years
    Nice. But the bad point is that you can't define a class constant this way.
  • Frank Nocke
    Frank Nocke about 12 years
    +1. I am going for this for years: const AtomicValue =42; public static $fooArray = ('how','di')
  • Akoi Meexx
    Akoi Meexx over 11 years
    While it seems ridiculous to me that we can't create immutable arrays in php, this provides a decent workaround.
  • Jürgen Paul
    Jürgen Paul over 11 years
    better stick to static variables in a class.
  • Ian Dunn
    Ian Dunn over 11 years
    This doesn't add anything to the accepted answer, so maybe it should be deleted?
  • Alix Axel
    Alix Axel over 11 years
    @IanDunn: I would argue that the accepted answer doesn't explain why, or that it doesn't add anything to my answer but... Feel free to vote to delete though.
  • Tomáš Zato
    Tomáš Zato over 11 years
    I don't really see the point of any string representation of desired array.
  • kojiro
    kojiro over 11 years
    @Gregoire you can if you pre-serialize the value. (ugh!)
  • Sophivorus
    Sophivorus about 11 years
    Too bad you can't do: $fruit = FRUITS[0];
  • Armfoot
    Armfoot almost 11 years
    Felipe, you can do $fruit = $my_fruits[0]... FRUITS is a string (not an array - it's the result of serializing an array), therefore you need to unserialize it in order to get back the array.
  • Saeed
    Saeed almost 11 years
    you can prevent exploding two times by doing : $explodeResult = explode(',' ,$const ); if(isset($explodeResult)[$index]){return $explodeResult[$index];}
  • MD. Sahib Bin Mahboob
    MD. Sahib Bin Mahboob almost 11 years
    @Saeed yup that is a nice point. I will update my answer accordingly
  • David J Eddy
    David J Eddy almost 11 years
    This was exactly what I needed to pass multiple values into an object that are user defined! I.E.: types of employees as an array.
  • noun
    noun over 10 years
    This code is elegant but pretty slow. It's far better using a public static class method that returns the array.
  • Con Antonakos
    Con Antonakos almost 10 years
    This is exactly what I was thinking. Is this not a legitimately good answer?
  • Drellgor
    Drellgor over 9 years
    This works really well with AngularJS because it consumes JSON. I feel like this is much better that the serialize answer, but is there some reason why serialize is better? Is it faster perhaps?
  • Chris Seufert
    Chris Seufert over 9 years
    If you are using the constant a lot, I would definitely avoid a function call, they are quite expensive. Static is the way to go.
  • Alex K
    Alex K over 9 years
    just putting a note here that in PHP 5.6 you can now have const arrays.. const fruits = ['apple', 'cherry', 'banana'];
  • Mario Awad
    Mario Awad over 9 years
    Yes serialize is technically faster. However, for small sets, which is what's needed mostly, I prefer this method as it's safer. When you unserialize, code might be executed. Even if in this case this is a very low risk, I think we should reserve the usage or unserialize for extreme cases only.
  • Andreas Bergström
    Andreas Bergström over 9 years
    This needs to be upvoted as all other answers are outdated or just written by misinformed users.
  • Jack
    Jack over 9 years
    Is that the only syntax? Are you able to use the old define function? define('ARRAY_CONSTANT', array('item1', 'item2', 'item3'));
  • Andrea
    Andrea over 9 years
    @JackNicholsonn Unfortunately you can't use define() here in PHP 5.6, but this has been fixed for PHP 7.0. :)
  • Ismael Miguel
    Ismael Miguel over 9 years
    @AndreasBergström No, this question is too new. This question was made in 2009! This syntax will be nearly useless for most users now-a-days. Almost anyone has PHP 5.6 on their servers. The other answers are perfectly fine since they also offer alternatives. The accepted answer is the only viable way so far, if you don't want to use classes.
  • Armfoot
    Armfoot about 9 years
    This solution was far more awesome than I expected: I only needed part of the array's values, therefore instead of simply getting the array, I used some parameters in the function. In my case Constants::getRelatedIDs($myID) gets me an inner array with just the values I needed (I also do some ID validation inside this function). @cseufert getting the whole array and filtering for each case would be much more expensive for me...
  • M H
    M H almost 9 years
    @IsmaelMiguel dont be so sure they all have 5.6. Anyone on windows server just now got the 5.6 sql server drivers from microsoft about a month ago.
  • Loenix
    Loenix over 8 years
    This solution should be DEPRECATED due to the lack of performance !
  • jeteon
    jeteon over 8 years
    This is a nice alternative to pipe separated values. I think saying a serialize()/unserialize() call is slow overstates the contribution it would make to the overall execution time for a script.
  • Damon
    Damon almost 8 years
    almost there! 8 more upvotes!! :p. Altho if this answer incoroporated the PHP < 5.6 answer it would be even more good
  • NullPointer
    NullPointer over 7 years
    I did same like you did. So was looking for performance optimization whether this is good or something else if better.
  • vaso123
    vaso123 over 7 years
    Aaaarrrgh... In PHP 5.6 you can define value of constant as a function returns value if you use define keyword. You can use arrays when you define it with const but no function returns value. And no option to mix it somehow. Only in php7. sigh...
  • Andrea
    Andrea over 7 years
    @vaso123 one workaround is to do something like: eval("const $constname = " . var_export($somevariable) . ";"); – not sure I'd recommend this though
  • vaso123
    vaso123 over 7 years
    @Andrea Lol... Never, no way. eval is evil. To define(serialize([...])); is does the job for me, luckily I have only 2 arrays and these arrays are not too big. I could write a helper class to get those values, I just want to use advantages of my IDE. Next time... when we will start use PHP 7.
  • Kamaldeep singh Bhatia
    Kamaldeep singh Bhatia over 7 years
    having a function (getArray) with private static member is best representation for constants as they can be changes 👍🏻
  • Admin
    Admin about 7 years
    @Loenix, This is said that you can create constant arrays since php 5.6, but if someone (like me) has earlier php, this is perfectly correct.
  • Admin
    Admin about 7 years
    Wow, I did not expected such way... I didn't even know about __get and __set... I must say that this method is great.
  • Loenix
    Loenix about 7 years
    @Soaku In this case, you should use the Ravi Hirani's solution or and explicit function returning an array, this one should be deprecated in all cases.
  • Admin
    Admin about 7 years
    @Loenix, why? This is the real way of storing array in constant, while the RaviHirani's solution isn't using real constant. And it's even longer in use than this. And how would you deprecate something which is just snippet?
  • Loenix
    Loenix about 7 years
    @Soaku because this is not storing an array but a string and you will have to unserialize it each time you use it. So prefer a function returning an array that is better for perfomances and this is a real constant-like solution.
  • Admin
    Admin about 7 years
    @Loenix, maybe, but his solution also requires some bonus typing everytime you use it, even if it isn't needed. Rikudou_Sennin's solution looks better,
  • Rikudou_Sennin
    Rikudou_Sennin about 7 years
    These are called magic methods, check php documentation about them.
  • Faris Rayhan
    Faris Rayhan over 6 years
    Ya i agree with this solution. As it is simple and easy to be understood...
  • miken32
    miken32 over 5 years
    We've been able to define arrays as constants for many years now, I don't think there's a lot of value to obtuse workarounds anymore.
  • puiu
    puiu about 5 years
    @miken32 while true, the provided solution is interesting, was not supplied by anyone else, and can be conceptually applied to other languages as needed (add it to your tool box)
  • klidifia
    klidifia about 4 years
    Short syntax obviously works for PHP7 as well, don't know why you wouldn't use it ([] instead of array()).
  • Andrea
    Andrea about 4 years
    Because it's what the original question did.