How to convert an array into independent function parameters?
P粉391677921
P粉391677921 2023-07-22 23:17:01
0
2
521

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粉391677921
P粉391677921

reply all(2)
P粉071602406

If I understand you correctly:

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

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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template