php how to generate dynamic list()?

前端 未结 4 1434

base on my understanding, this how list() work.

list($A1,$A2,$A3) = array($B1,B2,B3);

So with the help of list() we can assign val

4条回答
  •  灰色年华
    2021-01-22 00:12

    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 
    \n"; $$key = $val; } var_dump($arrindex0, $someprefix_0, $someprefix_1);

    Result

    string 'apple' (length=5)
    string 'banana' (length=6)
    string 'pear' (length=4)
    

提交回复
热议问题