Page 1 of 1

define() an array?

Posted: Wed May 24, 2006 1:12 pm
by Skara
Is this possible...

Code: Select all

define('FOO',array(1,2,3));
...somehow? Doesn't work as is. FOO[1] gives unexpected [.

Posted: Wed May 24, 2006 1:17 pm
by PrObLeM
short answer: no.

There are many ways to work around it, here is one right from the manual.
You can't use arrays in constants, so I came up with this two line function to get around it.

<?php

function const_array($constant) {
$array = explode(",",$constant);
return $array;
};
?>

So now if you define a constant like

<? define('myconstant','item1,item2,item3') ?>

and then use my function

<? $myarray = const_array(myconstant); ?>

$myarray will now contain an array with
item1
item2
item3
Another way, I like this one better

Code: Select all

/*Constants MUST evaluate to scalar values only.
You are encouraged to use serialize/unserlialize
to store/retrieve an array in a constant:*/

define('CONST',serialize(array('a','b','foo'=>'bar')));
var_dump(CONST);
var_dump(unserialize(CONST));

Posted: Wed May 24, 2006 1:36 pm
by Skara
Thanks. Doesn't help any, but at least I know. ;)