I want to be able to generate some constants from an array. So something like this:
foreach ($array as $key => $value) {
define($key,$value);
}
Is there a simple way to do this?
I want to be able to generate some constants from an array. So something like this:
foreach ($array as $key => $value) {
define($key,$value);
}
Is there a simple way to do this?
You're already doing this in your code. Or d you mean like this?
$array = array("sparkles" => "pretty");
foreach($array as $key=>$value) {
${$key} = $value;
}
echo $sparkles; //pretty
An alternative, if you have many constants to define, and APC installed:
$constants = array(
'ONE' => 1,
'TWO' => 2,
'THREE' => 3,
);
apc_define_constants('numbers', $constants);
(straight example from apc_define_constants
)
Assuming PHP 5.3 or higher, you could do:
array_walk($array, function ($value, $key) {
define($key, $value);
});
or
array_walk(array_flip($array), 'define');
But honestly, I would just use your current method.
Also you can try to use extract
function. It produces the same result (almost) as in njk's answer