PHP - populate an array with variables by loop

谁说我不能喝 提交于 2021-01-28 07:11:43

问题


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?


回答1:


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 "\n";  //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!
}



回答2:


Even if its not best practice, this should work:

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

function arrayDefine($varName, $max) {
    $items = array();
    for ($i = 1; $i <= $max; ++$i){
        $var = $varName.$i;
        global $$var;
        $items[$i] = $$var;
    }
    return $items;
}

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



回答3:


function arrayFunction()
{
    $str1 = "one";
    $str2 = "two";
    $str3 = "three";
    $array = array($str1, $str2, $str3);


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

    }

}

arrayFunction();



回答4:


I think this will work:

$str1 = 'one';
$str2 = 'two';
$str2 = 'three';

for($i=1;$i<100;$i++){
  $varName = 'str' . $i;
  $returnArray[$varName] = $$varName;
}

However, if you are making a function, remember, that it won't have access to $str1, $str2, etc... Because they are in the GLOBAL scope, not the function scope (and unlike most languages ?! (Atleast the ones I know)) GLOBALs are not accessible within a function unless you say "global".

So you'll need to use Tomas' Code.



来源:https://stackoverflow.com/questions/21393760/php-populate-an-array-with-variables-by-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!