php 通过在php中连接字符串来创建变量名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16955258/
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
creating variable name by concatenating strings in php
提问by Pradeep
I have a file named questions.php with an array as follows :
我有一个名为 questions.php 的文件,其中包含一个数组,如下所示:
$question12 = array("Which is the tallest mountain","Mt Everest");
I am including this file in another file as follows :
我将此文件包含在另一个文件中,如下所示:
require_once('questions.php');
$var = 12;
$question = '$question'.$var.'[0]';
echo $question;
The above code just outputs the following string(not the contents of the variable):
上面的代码只是输出如下字符串(不是变量的内容):
$question12[0]
But I want the variable $questionto contain the string present in $question12[0].
但我希望变量$question包含$question12[0] 中存在的字符串。
How do I accomplish this?
我该如何实现?
回答by xdazz
Variable variable is not recommended, but the answer is below:
不推荐变量变量,但答案如下:
$question = ${'question'.$var}[0];
回答by Vivek Sadh
Just use $question12[0]. It will give you the desired output.
只需使用 $question12[0]。它将为您提供所需的输出。
Using the $var you can do it like this:-
使用 $var 你可以这样做:-
$question = ${'question'. $var}[index]
;
$question = ${'question'. $var}[index]
;
回答by Jordan Doyle
You're looking for variable variables.
您正在寻找可变变量。
$id = 12;
$q = "question{$id}";
$q = $$q[0];
You should seriously consider looking into multidimensional arrays to stop having multiple arrays.
您应该认真考虑研究多维数组以停止使用多个数组。
回答by Hanky Panky
Sorry, im going to get some hate for mentioning something evil
but still it is one of the options
抱歉,我会因为提到某事evil
而讨厌,但它仍然是一种选择
<?php
$question12 = array("Which is the tallest mountain","Mt Everest");
$var = 12;
$question = '$question'.$var.'[0]';
eval("echo $question;");
?>
P.S: eval()is that evil
PS: eval()就是这样evil