数组值作为变量名称

时间:2015-01-09 14:54:57

标签: php arrays loops

我最近发现了另一个stackoverflow问题,其中包含以下内容:

$segments = array(
"key1"    =>"111",
"key2"    =>"222",
"key3"    =>"333",
"key4"    =>"444"
);

我想要这些:

$key1 has the value of  "111";

$key2 has the value of  "222";

$key3 has the value of  "333";

$key4 has the value of  "444";

答案是使用extract($segments)

我想实现一些不相似的东西,我有以下数组

 $test = array('hello','world');

理想情况下,我想循环遍历它们并使用数组值作为变量名称,例如:

$test2 = array('hello','world');
foreach($test as $v)
{
   $$v = $v;
}

因此,在循环之后,我可以回复说$hello,这将导致输出hello

任何人都可以告诉我如何实现这一目标。如果有一个没有循环的方法等那么好。我意识到我的例子可以用不同的方式完成,所以这个问题是多余的,但我出于好奇和我的知识而问。

1 个答案:

答案 0 :(得分:2)

数组是更好的,你很少需要extract或变量变量,但这是一种方式(仅为了知识):

$test2 = array('hello','world');
extract(array_combine($test2, $test2));
相关问题