Alternative for define array php

17,091

Solution 1

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);

Solution 2

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.

Solution 3

If you are on php5.6 and you know that this version onward php does support arrays as constants. But you are still getting the following warning...

Warning: Constants may only evaluate to scalar values

Then you are in luck. Its because the method of defining array constants using define() is still not introduced in this version and has only been introduced inside phpv7.xx

So instead you can use the const keyword.

const MY_SUPER_CONSTANT = array(
    'cool_key'      => 'Cool Value',
    'ultra_fab_key' => 'Fabulous Value',
);
Share:
17,091
Anoniem Anoniem
Author by

Anoniem Anoniem

Updated on June 26, 2022

Comments

  • Anoniem Anoniem
    Anoniem Anoniem almost 2 years

    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.

  • Piseth Sok
    Piseth Sok about 3 years
    That is woking for me.Thanks