php 如何在循环中更改php变量名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6234864/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:43:40  来源:igfitidea点击:

how to change php variable name in a loop?

phpvariablesloopsfor-loop

提问by user701510

Lets say I have a variable called $file and the for loop: for($i=1; $i <= 5; $i++) {}

假设我有一个名为 $file 的变量和 for 循环: for($i=1; $i <= 5; $i++) {}

For each iteration of the for loop, the $ivalue will be appended to the $filevariable name so after the for loop ends, I should have five variables: $file1, $file2, $file3, $file4, and $file5.

对于for循环每次迭代中,$i值将被追加到$file变量名,以便以后的循环结束,我应该有五个变量:$file1$file2$file3$file4,和$file5

回答by Yuri Stuken

Use ${'varname'} syntax:

使用${'varname'} 语法

for($i=1; $i <= 5; $i++) {
    ${'file' . $i} = $i;
}

However, it's often better to use arrays instead of this.

但是,使用数组通常比使用数组更好。

回答by Hammerite

There isa way to do this:

这里一个办法做到这一点:

for($i = 1; $i <= 5; $i++) {
    ${'file'.$i} = ...;
}

But it is a bad ideato do this. Why is it a bad idea? Because this is what arraysare meant for. Do this instead:

但这样做是个坏主意。为什么这是一个坏主意?因为这就是数组的用途。改为这样做:

for($i = 1; $i <= 5; $i++) {
    $file[$i] = ...;
}

(NB. It is the usual convention to start array keys at 0 rather than 1, but you do not have to do so.)

(注意。通常的惯例是从 0 而不是 1 开始数组键,但您不必这样做。)

回答by bumperbox

it is possible to do what you want, but creating variables on the fly seems an unusual way to solve a problem like this (i could be wrong)

可以做你想做的事,但动态创建变量似乎是解决此类问题的一种不寻常的方式(我可能是错的)

I would suggest storing the filenames in an array, that way you can easily iterate over the files later on, or add an extra file and not have to change any hardcoded variable names

我建议将文件名存储在一个数组中,这样您以后可以轻松地遍历文件,或者添加一个额外的文件而不必更改任何硬编码的变量名称

    $myfiles = array();

    for ($i=1; $i<=5; $i++) {
       $myfiles["file$i"] = "value set in loop";
    }

    //if you want to use the values later
    $file5_value = $myfiles["file5"];

    //if you want to loop through them all
    foreach ($myfiles as $key => $val) {
      echo "$key -> $val\n";
    }

回答by jeremysawesome

You can use an array as well. It doesn't have the same exact affect, but it is generally what I see used in these situations.

您也可以使用数组。它没有完全相同的影响,但通常是我在这些情况下看到的。

for($i=1; $i <= 5; $i++) {
    $file[$i] = $i;
}

回答by Brad Christie

See PHP's manual on Variable Variables.

请参阅 PHP 的Variable Variables手册。

$var_name = '';
for ($i = 0; $i < 5; $i++)
{
  $var_name = 'file' . $i;

  // reference $$var_name now.
  $$var_name = 'foo';
}

var_dump($file1);
var_dump($file2);
var_dump($file3);
var_dump($file4);
var_dump($file5);

demo

演示