views:

157

answers:

3

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.

A: 

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}"; }
Lance Rushing
Not *technically* correct (call_user_func_array is how you are supposed to do this type of behavior, but this is very clever. +1
Christopher W. Allen-Poole
Good suggestion. You can then use a standard function call (without call_user_func_array) which keeps the code clean. The only pitfall is that list requires you to hard-code the arguments ... list($a, $b) ... while I don't the number of array values in advance.
Kristoffer Bohmann
+9  A: 

if I understand you correctly:

$arr = array("alpha", "beta");
call_user_func_array('my_func', $arr);
valya
Exactly. Thanks.
Kristoffer Bohmann
A: 

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

Nicolas