I'm looking for an alternative for define('name', array)
as using an array in define gives me this error:
Constants may only evaluate to scalar values in ...
The array I'm mentioning contains strings only.
An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments. The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ) .
PHP Constant Arrays In PHP7, you can create an Array constant using the define() function.
=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass .
From php.net...
The value of the constant; only scalar and null values are allowed. Scalar values are integer, float, string or boolean values. It is possible to define resource constants, however it is not recommended and may cause unpredictable behavior.
But You can do with some tricks :
define('names', serialize(array('John', 'James' ...)));
& You have to use unserialize() the constant value (names) when used. This isn't really that useful & so just define multiple constants instead:
define('NAME1', 'John');
define('NAME2', 'James');
..
And print like this:
echo constant('NAME'.$digit);
This has changed in newer versions of PHP, as stated in the PHP manual
From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant.
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