search

Home  >  Q&A  >  body text

How to convert an array into independent function parameters?

I want to use the values ​​in the array as independent parameters in the function call. Example:

// Values "a" and "b"
$arr = array("alpha", "beta");
// ... are to be inserted as $a and $b.
my_func($a, $b)
function my_func($a,$b=NULL) { echo "{$a} - {$b}"; }

The number of values ​​in the array is unknown.

Possible solutions are:

  1. I can pass the array as a single parameter, but would prefer to pass it as multiple independent function parameters.

  2. Concatenate the arrays into comma-separated strings using the implode() function. (Fails because it's just a string.)

  3. Use a single parameter:

    $str = "'a','b'";
    function goat($str);  // $str needs to be parsed as two independent values/variables.
  4. Use eval()?

  5. Traverse the array?

Suggestions are welcome. Thanks.

P粉391677921P粉391677921553 days ago548

reply all(2)I'll reply

  • P粉071602406

    P粉0716024062023-07-23 22:33:24

    If I understand you correctly:

    $arr = array("alpha", "beta");
    call_user_func_array('my_func', $arr);

    reply
    0
  • P粉063039990

    P粉0630399902023-07-23 16:28:10

    This question is quite old, but has more direct support in PHP 5.6 version.

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

    $arr = array("alpha", "beta");
    my_func(...$arr);

    reply
    0
  • Cancelreply