-2

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jon Hester
  • 189
  • 1
  • 1
  • 11

4 Answers4

0

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
Kermit
  • 33,827
  • 13
  • 85
  • 121
  • 1
    Those are variables, not constants – nice ass Feb 08 '13 at 19:46
  • It works as I wrote it. I haven't needed to do this before and there was another bug in another part of the code preventing it from working. I feel pretty stupid assuming it couldn't work as I wrote it, but appreciate all the help. – Jon Hester Feb 08 '13 at 19:57
0

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)


Edit: an interesting read about performance

nice ass
  • 16,471
  • 7
  • 50
  • 89
0

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.

Supericy
  • 5,866
  • 1
  • 21
  • 25
-1

Also you can try to use extract function. It produces the same result (almost) as in njk's answer

See: http://php.net/manual/en/function.extract.php

Vladimir Posvistelik
  • 3,843
  • 24
  • 28
  • Oh, downvoting... Ok, it doesnt create any constants. To create constant in runtime you can try to use `eval` construction - but its a bad idea. Also you can look at my answer to the similar question: http://stackoverflow.com/questions/12113663/dynamic-constants-in-php/12117642#12117642 – Vladimir Posvistelik Feb 08 '13 at 19:52
  • What does eval have to do with creating a constant? – Supericy Feb 08 '13 at 19:57