Is there a way to define a constant array in PHP?
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.
Answer:
define('SOMEARRAY', serialize(array(1,2,3)));
$is_in_array = in_array($x, unserialize(SOMEARRAY));
That’s the closest to an array constant.
Answer:
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.
Answer:
don’t think you can. But you can always try searching.
Tags: phpphp