PHP Constants Containing Arrays?
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
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'
Nick Heiner
JS enthusiast by day, horse mask enthusiast by night. Talks I've Done
Updated on July 08, 2022Comments
-
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 over 9 yearsPHP 5.6 supports constant arrays, see my answer below.
-
ziGi over 9 yearsWhen 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 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 almost 13 yearsJust want to say I love this solution :)
-
Gregoire almost 13 yearsNice. But the bad point is that you can't define a class constant this way.
-
Frank Nocke about 12 years+1. I am going for this for years:
const AtomicValue =42; public static $fooArray = ('how','di')
-
Akoi Meexx over 11 yearsWhile it seems ridiculous to me that we can't create immutable arrays in php, this provides a decent workaround.
-
Jürgen Paul over 11 yearsbetter stick to static variables in a class.
-
Ian Dunn over 11 yearsThis doesn't add anything to the accepted answer, so maybe it should be deleted?
-
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 over 11 yearsI don't really see the point of any string representation of desired array.
-
kojiro over 11 years@Gregoire you can if you pre-serialize the value. (ugh!)
-
Sophivorus about 11 yearsToo bad you can't do:
$fruit = FRUITS[0];
-
Armfoot almost 11 yearsFelipe, 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 almost 11 yearsyou can prevent exploding two times by doing : $explodeResult = explode(',' ,$const ); if(isset($explodeResult)[$index]){return $explodeResult[$index];}
-
MD. Sahib Bin Mahboob almost 11 years@Saeed yup that is a nice point. I will update my answer accordingly
-
David J Eddy almost 11 yearsThis 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 over 10 yearsThis code is elegant but pretty slow. It's far better using a public static class method that returns the array.
-
Con Antonakos almost 10 yearsThis is exactly what I was thinking. Is this not a legitimately good answer?
-
Drellgor over 9 yearsThis 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 over 9 yearsIf 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 over 9 yearsjust putting a note here that in PHP 5.6 you can now have const arrays..
const fruits = ['apple', 'cherry', 'banana'];
-
Mario Awad over 9 yearsYes 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 over 9 yearsThis needs to be upvoted as all other answers are outdated or just written by misinformed users.
-
Jack over 9 yearsIs that the only syntax? Are you able to use the old define function? define('ARRAY_CONSTANT', array('item1', 'item2', 'item3'));
-
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 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 about 9 yearsThis 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 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 over 8 yearsThis solution should be DEPRECATED due to the lack of performance !
-
jeteon over 8 yearsThis 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 almost 8 yearsalmost there! 8 more upvotes!! :p. Altho if this answer incoroporated the PHP < 5.6 answer it would be even more good
-
NullPointer over 7 yearsI did same like you did. So was looking for performance optimization whether this is good or something else if better.
-
vaso123 over 7 yearsAaaarrrgh... 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 withconst
but no function returns value. And no option to mix it somehow. Only in php7. sigh... -
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 over 7 years@Andrea Lol... Never, no way.
eval
is evil. Todefine(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 over 7 yearshaving a function (getArray) with private static member is best representation for constants as they can be changes 👍🏻
-
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 about 7 yearsWow, I did not expected such way... I didn't even know about
__get
and__set
... I must say that this method is great. -
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 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 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 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 about 7 yearsThese are called magic methods, check php documentation about them.
-
Faris Rayhan over 6 yearsYa i agree with this solution. As it is simple and easy to be understood...
-
miken32 over 5 yearsWe'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 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 about 4 yearsShort syntax obviously works for PHP7 as well, don't know why you wouldn't use it ([] instead of array()).
-
Andrea about 4 yearsBecause it's what the original question did.