dppx9253 2017-06-24 06:30
浏览 16
已采纳

可以用数组值更改PHP变量吗?

Here i have an array in PHP. how can i assign array1 value as a variable name? i want to call the variable by the name in the array.

$array1 = array("comp1", "comp2", "comp3");

for example: when i use foreach loop to loop, i want the variable name to be concatenate with the value in the array.

$var + comp1 >>> ($varcomp1)
$var + comp2 >>> ($varcomp2)

or even

$varcomp + 1 >>> ($varcomp1)
$varcomp + 2 >>> ($varcomp2)

this may sound stupid but i have no idea if this is even possible. or is there any other better way to do this so that i can call the variables with different value?

sorry if this post has been asked because i do not know what is the term to search for this type of question.

  • 写回答

3条回答 默认 最新

  • douhuan6305 2017-06-24 06:38
    关注

    If you add $$ in first of string variable, you can define new variable.

    <?php
    
    $array1 = array("comp1", "comp2", "comp3");
    
    foreach($array1 as $value) {
        ${"var" . $value} = "test $value variable";
    }
    
    echo $varcomp1; // outpu: "test comp1 variable"
    echo $varcomp2; // outpu: "test comp2 variable"
    echo $varcomp3; // outpu: "test comp3 variable"
    ?>
    

    Example for define variable with string variable:

    $string = 'hello';
    $$string = 'new variable'; //define $hello variable
    echo $hello; //Output: "new variable"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?