Is there a way to define a constant array in PHP?
Asked
Active
Viewed 3,043 times
7
-
It can be used to emulate enums, although everything can be done with classes and a bit of reflection. – Itay Moav -Malimovka Feb 11 '10 at 01:23
4 Answers
8
define('SOMEARRAY', serialize(array(1,2,3)));
$is_in_array = in_array($x, unserialize(SOMEARRAY));
That's the closest to an array constant.

Peter Mortensen
- 30,738
- 21
- 105
- 131

useless
- 1,876
- 17
- 18
-
Thanx: did this and worked great define("DEF_ARR", serialize(array("1", "a", "From.ME.to.YOU"))); foreach (unserialize(DEF_ARR) as $k=>$v) { echo "Key: ".$k." VALUE: ".$v."\n"; } – Phill Pafford May 27 '10 at 16:57
6
No, it's not possible. From the manual: Constants Syntax
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.
If you need to set a defined set of constants, consider creating a class and filling it with class constants. A slightly modified example from the manual:
class MyClass
{
const constant1 = 'constant value';
const constant2 = 'constant value';
const constant3 = 'constant value';
function showConstant1() {
echo self::constant1 . "\n";
}
}
echo MyClass::constant3;
Also check out the link GhostDog posted, it's a nice workaround.

Pekka
- 442,112
- 142
- 972
- 1,088
2
You can not, but you can just define static array in a class and it would serve you just the same, just instead of FOO you'd write Foo::$bar.

StasM
- 10,593
- 6
- 56
- 103
1
don't think you can. But you can always try searching.

Peter Mortensen
- 30,738
- 21
- 105
- 131

ghostdog74
- 327,991
- 56
- 259
- 343
-
-
1can you review your answer? There is a seemingly contradiction between "don't think you can" and the reference's "This class provides an alternative solution that can be used to also declare array values as constants." – Peter Mortensen Dec 07 '10 at 10:17