Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 982
Anoniem Anoniem Avatar asked Oct 18 '13 07:10

Anoniem Anoniem


People also ask

How do you declare an array in PHP?

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, ) .

Can I define array in constant PHP?

PHP Constant Arrays In PHP7, you can create an Array constant using the define() function.

What does => mean in PHP array?

=> 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 .


2 Answers

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);
like image 164
Jenson M John Avatar answered Sep 20 '22 00:09

Jenson M John


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.

like image 45
hutch Avatar answered Sep 20 '22 00:09

hutch