PHP动态变量的简单连接

时间:2013-01-05 22:31:34

标签: php concatenation variables

如何将动态var加入现有var?

例如:

我的代码:

<?

// Gets value from url. In this example c is 1.

$c = $_GET[c];  

// Multiple static questions will be pulled from a list. 
// I use two as an example below. 

$Q1 = "Is this question one?";
$Q2 = "so this must be question two then?"

echo "$c: ";
echo "Q$c";  // returns "Q1" but not the string above.
echo '$Q.$c"; // returns the val 1

?>

如何将两者结合在一起并让它返回相应的字符串?

4 个答案:

答案 0 :(得分:4)

使用包含多个值的array代替动态变量名。

$num = $_GET['c'];

$questions = array(
    "Is this question one?",
    "so this must be question two then?"
);

echo "$num: ";
echo "Q$num";
echo $questions[$num];

有很多很多理由喜欢将数组放到"variable variables"。一个是循环遍历数组中的所有项目:

foreach ($questions as $num => $question) {
    echo "Q$num: $question\n";
}

另一个是您可以计算数组的大小。

echo "There are " . count($questions) . " total questions.";

另一个是您可以轻松修改它们。有lots and lots and lots种操作数组的方法,你永远不能用变量变量之类的粗略工具。

// Add a new question to the array.
$questions[] = 'Question 3: Who are you?!';

// Remove duplicate questions.
$questions = array_unique($questions);

答案 1 :(得分:2)

看起来你真正想要的是array

$questions = array("Question 0", "Question 1", "Question 2");
$q = 1;
echo $questions[$q]; //"Question 1"

否则,你将不得不使用一些var-var讨厌的黑客(不要这样做):

echo ${'Q' . $c};

此外,$_GET[c]应为$_GET['c'],除非c实际上是constant(我希望不是c因为c是一个可怕的名字不变)。您应该使用isset,而不是假设$_GET

中存在$questions = array("Question 0", "Question 1", "Question 2"); $c = (isset($_GET['c'])) ? (int) $_GET['c'] : null; if (isset($questions[$c])) { echo "The question is: " . $questions[$c]; } else { echo "The question was not found"; } 密钥

完整示例:

<?

您可能也应该了解short open tags的缺点。如果服务器禁用它们,那么所有的PHP代码都会破坏。输入3个额外字符似乎不值得冒这个风险。 (虽然当然很容易批量查找/替换<?php - &gt; {{1}}。)

答案 2 :(得分:0)

我不确定我的意思是什么,但我认为这是anwer:

<?php

$var = "Q".$_GET['c'];

echo $$var; // take care of the double dollar sign

?>

但当然更优选数组

答案 3 :(得分:0)

你可以使用这样的php eval()函数:

eval("echo \$Q$c;");

但是您应该注意不要在未经验证的情况下放置用户数据,因为这可能会导致安全问题。