php how to generate dynamic list()?

做~自己de王妃 提交于 2019-12-02 01:42:43

If you have a variable number of elements, use arrays for them! It does not make sense to extract them into individual variables if you do not know how many variables you'll be dealing with. Say you did extract those values into variables $kid1 through $kidN, what is the code following this going to do? You have no idea how many variables there are in the scope now, and you have no practical method of finding out or iterating them next to testing whether $kid1 through $kidN are isset or not. That's insane use of variables. Just use arrays.

Having said that, variable variables:

$i = 1;
foreach ($array as $value) {
    $varname = 'kid' . $i++;
    $$varname = $value;
}

You can create a lambda expression with create_function() for this. The list() will be only accessible within the expression.

This creates variables $A1, $A2, .... $AN for each element in your array:

$list =  array("a", "b", "c", "d");

extract(array_combine(array_map(function($i) {
        return "A" . $i;
    }, range(1, count($list))), $list));

echo implode(" ", array($A1, $A2, $A3, $A4)), PHP_EOL;

You can modify the name of the variables in the array_map callback. I hope I'll never see code like that in production ;)

This is not what PHP's list is meant for. From the official PHP docs

list is not really a function, but a language construct. 
list() is used to assign a list of variables in one operation.

In other words, the compiler does not actually invoke a function but directly compiles your code into allocations for variables and assignment.

  • You can specifically skip to a given element, by setting commas as follows:

    list($var1, , $var2) = Array($B1, B2, B3);

    echo "$var1 is before $var2 \n";

  • or take the third element

    list( , , $var3) = Array($B1, B2, B3);

(I am assuming B2, B3 are constants? Or are you missing a $?)

Specifically using list, you can use PHP's variable variables to create variables from an arbitrary one-dimensional array as follows:

$arr = array("arrindex0" => "apple", "banana", "pear");
reset($arr);
while (list($key, $val) = each($arr)) {
    $key = is_numeric($key) ? "someprefix_" . $key : $key;
    echo "key sdf: $key <br />\n";
    $$key = $val;
}
var_dump($arrindex0, $someprefix_0, $someprefix_1);

Result

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