Kristoffer Bohmann
Kristoffer Bohmann

Reputation: 4094

Turn array into independent function arguments - howto?

I want to use values in an array as independent arguments in a 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 are unknown.

Possible solutions:

  1. I can pass the array as a single argument - but would prefer to pass as multiple, independent function arguments.

  2. implode() the array into a comma-separated string. (Fails because it's just one string.)

  3. Using 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 appreciated. Thanks.

Upvotes: 22

Views: 9876

Answers (4)

Jay Paroline
Jay Paroline

Reputation: 2527

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

Upvotes: 36

Nicolas
Nicolas

Reputation: 2186

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

Upvotes: 0

Valentin Golev
Valentin Golev

Reputation: 10095

if I understand you correctly:

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

Upvotes: 27

Lance Rushing
Lance Rushing

Reputation: 7640

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}"; }

Upvotes: 0

Related Questions