13

I have this array, $display_vars, and I want to split it into separate variables, so each variable's name is the array key, and it's value is the value, so to speak. So if the array was like this:

$display_vars = array(
'title' => 'something',
'header' => 'something else'
);

Then I want to end up with the equivalent of this:

$title = 'something';
$header = 'something else';

Can you think of any way I can possibly do this?

1

4 Answers 4

15

The extract function does exactly this.

See it in action (includes bonus reference to get_defined_vars).

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

Comments

8

extract()

Be mindful about overwriting variables of the same name in the current scope. Read up on the second parameter if this is a concern.

Comments

5

Use

extract($display_vars);

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

Comments

-1

Why don't you use just access it using the same array ? Calling a function like extract is just an overload.

<?php
$display_vars = array(
'title' => 'something',
'header' => 'something else'
);

echo $display_vars['title']; //something
echo $display_vars['header']; //something else

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.