Skip to content
Advertisement

Alternative for define array php

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement