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