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条)

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案