1

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".

0

4 Answers 4

8

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
5

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

Comments

4
${'setting'} = "thevalue";

Comments

1

It may be evil, but there is always eval.

$str = "setting";
$val = "thevalue";
eval("$" . $str . " = '" . $val . "'");

2 Comments

There are so many ways of doing it in PHP without eval().
Absolutely true, just one (not so great) method of doing things.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.