[英]How combine a variable and a string to form a new variable?
Is it possible to combine a variable and a string to a new variable and echo it? 是否可以将变量和字符串组合到一个新变量并回显它?
I have the following string: 我有以下字符串:
$string = '01001'
Trying something like: 尝试类似的东西:
$var = $_$string
Ultimately I want to end up with a var like $_01001
that I can print. 最终我希望得到一个像我可以打印的$_01001
那样的var。 So if I have a bunch of data like: 所以,如果我有一堆数据,如:
$_01001 = 'foo'; $_01002 = 'bar'; $_01003 = 'fooz'; $_01004 = 'barz';
So echo $_01001;
所以echo $_01001;
would produce foo
... thanks in advance. 会产生foo
...先谢谢。
Yes you can use. 是的,你可以使用。 have a look on below example: 看看下面的例子:
$_01001 = 'foo';
$_01002 = 'bar';
$string1 = '01001';
$string2 = '01002';
echo ${"_$string1"};
echo ${"_$string2"};
Output: foobar
输出: foobar
mode detail available at Variable of variable 变量变量可用的模式详细信息
$string = '01001';
$vals = [
'01001' => 'foo',
'01002' => 'bar',
'01003' => 'fooz',
'01004' => 'barz',
];
echo $vals[$string]; // produces "foo"
Yah, I know, boring and lacking magic. 是的,我知道,无聊而且缺乏魔力。 But readable maintainable code is often boring and magicless. 但可读的可维护代码通常很无聊而且没有魔力。 Variable variables voodoo does exist in PHP but will just distract future readers/maintainers (including yourself 1+ weeks from now) from what you're really trying to do in your logic. 变量变量voodoo确实存在于PHP中,但它会分散你未来的读者/维护者(包括你自己现在1周以后)在你的逻辑中真正想做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.