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 计算二重积分∫∫e^(x+y)dxdy,其中0≤x≤1,0≤y≤1,试分别用复合辛普森公式(取n=4)以及高斯求积公式(取n=4)计算积分 给出matlab程序
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的