动态分配变量

时间:2018-07-11 10:24:12

标签: php

比如说我有这个

$word = "Hello";
$word1 = "my";
$word2 = "name is";
$word3 = "Shankar";

我希望能够在循环中调用每个变量名,并使用每个变量名后缀的数字来标识它们

这就是我所做的

$x = '';

while($x <= 3){
    $y = $word . $x;
    $x++;
    echo $y . "<br>";
}

但是我一直得到这个结果

Hello
Hello1
Hello2
Hello3

这就是我想要的

Hello
my
name is
Shankar

3 个答案:

答案 0 :(得分:3)

更改

$y = $word . $x;

$y = ${"word" . $x};

答案 1 :(得分:2)

我认为这将帮助您实现目标

$prefix = 'word';
$x = '';
while($x <= 3){
    $variable = $prefix.$x;
    $output = $$variable; //by adding the dollar sign you have then refered to it as a variable
    echo $output . '<br />';
    $x++;
}

查看此内容以获取更多知识http://php.net/manual/en/language.variables.variable.php

答案 2 :(得分:2)

始终使用数组存储数据集。它将代码简化为:

$words = ["Hello", "my", "name is", "Shankar"];
echo implode("\n", $words);