tags:

views:

69

answers:

4

Hey guys,

How do I go about setting a string as a literal variable in PHP? Basically I have an array like

$data['setting'] = "thevalue";

and I want to convert that 'setting' to $setting so that $setting becomes "thevalue".

Thanks for any help!

+5  A: 

See PHP variable variables.

Your question isn't completely clear but maybe you want something like this:

//Takes an associative array and creates variables named after
//its keys
foreach ($data as $key => $value) {
    $$key = $value;
}
Artelius
This is what I took the user's question to mean as well.@iamdadude, $$key is a "variable variable"You can set the name of a variable to be the value of another variable with the double dollar sign syntax.
Chris Sobolewski
works. Thanks a lot =)
Raphael Caixeta
+2  A: 
${'setting'} = "thevalue";
Ignacio Vazquez-Abrams
+1  A: 

It may be evil, but there is always eval.

$str = "setting";
$val = "thevalue";
eval("$" . $str . " = '" . $val . "'");
Tom
There are *so* many ways of doing it in PHP *without* `eval()`.
Ignacio Vazquez-Abrams
Absolutely true, just one (not so great) method of doing things.
Tom
+2  A: 

extract() will take the keys of an array and turn them into variables with the corresponding value in the array.

Ignacio Vazquez-Abrams