3

Possible Duplicate:
Array to named variables

How can I convert an array like this

$data = array(
    'name' => 'something',
    'another' => 'variable'
);

to

$name = 'something';
$another = 'variable';

Is there a way how I can do this without looping?

3
  • Can you give us more information on what you are trying to achieve at a higher level? This seems like a strange requirement. What is the scenario? Perhaps we can suggest a better overall solution for you. Commented Feb 2, 2012 at 13:27
  • @ralfe It's not that strange of a request necessarily. A lot of templating is done by passing an array to the method that grabs the template file, and then extract()s the values so you don't have to reference them by an array name. Commented Feb 2, 2012 at 13:29
  • Regarding the vague security conjectures: You can use EXTR_SKIP, EXTR_PREFIX or array_intersect_key to restrain the extracted variables. (You know, should it be user input at all.) Commented Feb 2, 2012 at 13:38

4 Answers 4

2

That what you want to do is basically bad idea. If you are extracting array with data that comes from user, it's easy to hack your site. But if you really want to do this, use extract function.

Sign up to request clarification or add additional context in comments.

Comments

1
extract($data);

http://php.net/extract

Comments

1

extract() can, but resist the impulse to do something so reckless and irresponsible.

2 Comments

+1 because you're the only one that warns that it's a terrible idea.
I don't see the question stating that the data comes from a user. It may be internal data passed between classes or functions. Creation and extraction of the array may be inefficient, but there may be cases where it's an elegant solution (although I haven't thought of any yet).
0

With extract, which defines a new variable for each key/value pair in the array:

extract($data);

echo $name; // something
echo $another; // variable

Comments