douao1579 2014-01-27 23:16
浏览 81
已采纳

PHP - 通过循环使用变量填充数组

I want to put my variables (the value of these variables) into an array. I have similar variable names, so I try to find a loop-based solution that gives the same output like that:

$str1 = "one";
$str2 = "two";
$str3 = "three";

$arr = array($str1, $str2, $str3);
foreach ($arr as $key => $value){
    echo "[", $key, "] = ", $value, "<br/>";
}

For the loop -based solution I tried this way but it doesn't let insert values into the array:

$str1 = "one";
$str2 = "two";
$str3 = "three";

function arrayDefine($varName, $max) {
    for ($i = 1; $i <= $max; ++$i){
        echo "$", $varName, $i;
        if ($i < $max){
            echo ", ";
        }
    }
}

$arrItems = arrayDefine(str, 3);
$arr = array($arrItems);
foreach ($arr as $key => $value){
    echo "[", $key, "] = ", $value, "<br/>";
}

The output of the first code block is:

[0] = one
[1] = two
[2] = three

but the second displays:

$str1, $str2, $str3[0] = 

What should I change/use in order to get the same result as with the first (not loop-based) solution?

  • 写回答

4条回答 默认 最新

  • doujiao7679 2014-01-27 23:33
    关注

    First thing you need to understand is the difference between printing some information to the output (eg. echo) and assigning values to variables.

    Your function just prints variable names to the output. However, these are strings. String is not equal to a piece of code once the program is running. This is the very basics of any sort of programming, and you must not try to do anything until variables are perfectly clear to you.

    Using $GLOBALS

    Now a solution. Since your variables are global, you can access them via php's $GLOBALS array. This would look like this:

    $str1 = "a";
    $str2 = "b";
    $str3 = "c";
    
    function createArray($name, $count) {
        $return_array  = array();
        for($i=0; $i<$count; $i++) {
            $return_array[$name.($i+1)] = $GLOBALS[$name.($i+1)];
        }
        return $return_array;
    } 
    
    print_r(createArray("str", 3));
    

    Generally, what you're doing is absurd. If you wan't to store some data so that all the data can be accessed, start with an array:

    array("a", "b", "c");
    or
    array("str1"=>"a", ...);
    

    Using eval()

    Also, many beginners tend to like the "evil" function. You could do it too. eval() turns a string to a piece of code. But, it's always a bad solution and I've always learned a better one when I learned more about programming. However, you can't know everything from the beginning, so here is a way how to produce most dangerous and insecure codes:

    function createArray($name, $count) { $return_array = array(); for($i=0; $i

    This is really dangerous and will cause trouble.

    Using $$ syntax

    I think that $$ approach proposed by ManiacTwister is the best. You can even turn a complicated string to a variable:

    echo ${"static_text" . $string};
    

    However, again, why not use arrays? This features should serve for debug purposes.

    Note on variable scopes.

    However, the variable scopes might be confusing, see an example:

    $x = 666;
    function printvar($name) {
         global $$name;  //Get the variable from global scope t the function scope
         echo $$name; //if $name = "x" this evaluates into echo $x
         echo "
    ";  //New line
    }
    printvar("x");  //Prints 666
    
    
    function aFunction() {
        $x = 13;  //This $x only exists betvween {} and has nothing to do with global $x = 666
        printvar("x");  //Still prints 666!
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器