Raphael Caixeta
Raphael Caixeta

Reputation: 7846

Extract associative array elements into individual variables

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

Upvotes: 1

Views: 7683

Answers (4)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799490

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

Upvotes: 5

Artelius
Artelius

Reputation: 49134

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;
}

Upvotes: 8

Tom
Tom

Reputation: 7091

It may be evil, but there is always eval.

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

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799490

${'setting'} = "thevalue";

Upvotes: 4

Related Questions