PHP 连接变量

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

PHP concatenate variable

phpvariablesconcatenation

提问by FlyingCat

Might be an easy question for you guys. can't find it on google.

对你们来说可能是一个简单的问题。在谷歌上找不到它。

I am trying to concatenate two variables name;

我正在尝试连接两个变量名称;

$i=0;
 for ($i=0;$i<5;$i++){
   if($array[$i]>0){

   $test.$i=//do something
   }else{
  $test.$i=//do something
  }
}

//echo $test0 gives me nothing.
//echo $test1 gives me nothing.

I know I can't use $test.$i but don't know how to do this.Any helps? Thanks!

我知道我不能使用 $test.$i 但不知道该怎么做。有帮助吗?谢谢!

回答by Simon

回答by Simon

I'm assuming that the variables are called $test0, $test1, ..., $test5. You can use the following:

我假设变量被称为 $test0、$test1、...、$test5。您可以使用以下内容:

${"test".$i}

Though, might I suggest that you make $test an array and use $i as the index instead? It's very odd to use $i as an index to loop through a list of variable names.

不过,我可以建议您将 $test 设为数组并使用 $i 作为索引吗?使用 $i 作为索引来遍历变量名列表是很奇怪的。

As an example, instead of:

举个例子,而不是:

$test0 = "hello";
$test1 = "world";

Use:

用:

$test[0] = "hello";
$test[1] = "world";

回答by nc3b

Try this:

尝试这个:

 for ($i=0;$i<5;$i++){
    $the_test = $test.$i;
    if($array[$i]>0){
        $$the_test=//do something
    }
    else{
        $$the_test=//do something
    }
}

回答by VDVLeon

This might work:

这可能有效:

$varName = $test . $i;
$$varName = ...

Can i ask where for this is neccesary?

我能问一下这是必要的吗?