php how to generate dynamic list()?

前端 未结 4 1401

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-21 23:56

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

    0 讨论(0)
  • 2021-01-22 00:00

    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;
    }
    
    0 讨论(0)
  • 2021-01-22 00:02

    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 ;)

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

    Result

    string 'apple' (length=5)
    string 'banana' (length=6)
    string 'pear' (length=4)
    
    0 讨论(0)
提交回复
热议问题