Splitting an array into the variables in php

别说谁变了你拦得住时间么 提交于 2020-01-02 01:05:10

问题


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


来源:https://stackoverflow.com/questions/8420103/splitting-an-array-into-the-variables-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!