define() an array?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

define() an array?

Post by Skara »

Is this possible...

Code: Select all

define('FOO',array(1,2,3));
...somehow? Doesn't work as is. FOO[1] gives unexpected [.
User avatar
PrObLeM
Forum Contributor
Posts: 418
Joined: Sun Mar 07, 2004 2:30 pm
Location: Mesa, AZ
Contact:

Post 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));
User avatar
Skara
Forum Regular
Posts: 703
Joined: Sat Mar 12, 2005 7:13 pm
Location: US

Post by Skara »

Thanks. Doesn't help any, but at least I know. ;)
Post Reply