php 如何连接PHP变量名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11740231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to concatenate PHP variable name?
提问by Smudger
I have a PHP for loop:
我有一个 PHP for 循环:
for ($counter=0,$counter<=67,$counter++){
echo $counter;
$check="some value";
}
What I am trying to achieve is use the for loop variable and append it to the name of another variable.
我想要实现的是使用 for 循环变量并将其附加到另一个变量的名称。
Bascially, I want the PHP output to be as follows for each row
基本上,我希望每一行的 PHP 输出如下
1
$check1="some value"
2
$check2="some value"
3
$check3="some value"
4
$check4="some value"
etc etc
I have tried $check.$counter="some value"but this fails.
我试过了,$check.$counter="some value"但这失败了。
How can I achieve this? Am I missing something obvious?
我怎样才能做到这一点?我错过了一些明显的东西吗?
回答by Tim Cooper
The proper syntax for variable variablesis:
变量变量的正确语法是:
${"check" . $counter} = "some value";
However, I highly discouragethis. What you're trying to accomplish can most likely be solved more elegantly by using arrays. Example usage:
但是,我非常不鼓励这样做。您尝试完成的任务很可能可以通过使用arrays来更优雅地解决。用法示例:
// Setting values
$check = array();
for ($counter = 0; $counter <= 67; $counter++){
echo $counter;
$check[] = "some value";
}
// Iterating through the values
foreach($check as $value) {
echo $value;
}
回答by Adunahay
You should use ${'varname'} syntax:
您应该使用 ${'varname'} 语法:
for ($counter=0,$counter<=67,$counter++){
echo $counter;
${'check' . $counter} ="some value";
}
this will work, but why not just use an array?
这会起作用,但为什么不只使用数组呢?
$check[$counter] = "some value";
回答by arma
This is usable in some cases. For example if your app has something like 2 language entries in DB.
这在某些情况下是可用的。例如,如果您的应用程序在数据库中有 2 个语言条目。
echo $this->{'article_title_'.$language};
That's much more usable than for example this;
这比例如这个更有用;
if($language == 'mylanguage1')
echo $this->article_title_mylanguage1;
else
echo $this->article_title_mylanguage2;
Obviously this is what you should not have to do in your multilingual app, but i have seen cases like this.
显然,这是您在多语言应用程序中不应该做的事情,但我见过这样的情况。
回答by Matt
An array would accomplish this.
一个数组可以实现这一点。
$check = array();
for($counter = 0; $counter <= 67; $counter++) {
$check[] = "some value";
var_dump($check[$counter]);
}

