Turn array into independent function arguments - howto?

前端 未结 4 950
遇见更好的自我
遇见更好的自我 2020-12-11 01:19

I want to use values in an array as independent arguments in a function call. Example:

// Values \"a\" and \"b\"
$arr = array(\"alpha\", \"beta\");
// ... ar         


        
相关标签:
4条回答
  • 2020-12-11 01:44

    This question is fairly old but there is finally more direct support for this in PHP 5.6+:

    http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list.new

    $arr = array("alpha", "beta");
    my_func(...$arr);
    
    0 讨论(0)
  • 2020-12-11 01:51

    if I understand you correctly:

    $arr = array("alpha", "beta");
    call_user_func_array('my_func', $arr);
    
    0 讨论(0)
  • 2020-12-11 01:58

    You can do that using call_user_func_array(). It works wonders (and even with lambda functions since PHP 5.3).

    0 讨论(0)
  • 2020-12-11 02:06

    try list()

    // Values "a" and "b"
    $arr = array("alpha", "beta");
    list($a, $b) = $arr;
    my_func($a, $b);
    
    function my_func($a,$b=NULL) { echo "{$a} - {$b}"; }
    
    0 讨论(0)
提交回复
热议问题