Splitting an array into the variables in php

2020-08-13 04:58发布

问题:

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:

The extract function does exactly this.

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



回答2:

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.



回答3:

Use

extract($display_vars);

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



回答4:

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