Is there a way to define a constant array in PHP?
PHP Constant Arrays In PHP7, you can create an Array constant using the define() function.
Arrays are Not Constants It defines a constant reference to an array. Because of this, we can still change the elements of a constant array.
PHP constants are name or identifier that can't be changed during the execution of the script except for magic constants, which are not really constants. PHP constants can be defined by 2 ways: Using define() function. Using const keyword.
A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined. To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name.
define('SOMEARRAY', serialize(array(1,2,3)));
$is_in_array = in_array($x, unserialize(SOMEARRAY));
That's the closest to an array constant.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With