Scott C Wilson
Scott C Wilson

Reputation: 20026

How do I pass a PHP function expecting varargs a string?

I have a PHP function which takes a variable number of arguments.

function foo() {
     $numargs = func_num_args(); 
     if ($numargs < 3) {
         die("expected number of args is 3, not " . $numargs);
     }  
...

If I call it like this:

   foo(1, 12, 17, 3, 5); 

it's fine, but if I call it like this:

   $str = "1, 12, 17, 3, 5"; 
   foo($str); 

it fails because it says I am only passing one argument. What change do I need to make if I would prefer not to change the function itself, just the calling convention.

-- update: to save the explode call, I simply built an array. And because the function was a member function, the calling convention was a bit different. So the code wound up being

$list = array(); 
$list[] = 1;
$list[] = 12;
$list[] = 17;
// etc. 
call_user_func_array(array($this, 'foo'), $list);

Thought this might be useful to someone else.

Upvotes: 3

Views: 652

Answers (2)

Jan Hančič
Jan Hančič

Reputation: 53931

This should do the trick:

$str = "1, 12, 17, 3, 5"; 
$params = explode(', ', $str );
call_user_func_array ( 'foo', $params );

call_user_func_array() allows you to call a function and passing it arguments that are stored in a array. So array item at index 0 becomes the first parameter to the function, and so on.

http://www.php.net/manual/en/function.call-user-func-array.php

update: you will have to do some additional processing on the $params array if you wish that the arguments will be integers (they are passed as strings if you use the above snippet).

Upvotes: 4

Mark Baker
Mark Baker

Reputation: 212412

$str = "1, 12, 17, 3, 5"; 
call_user_func_array('foo',explode(',',$str));

Upvotes: 3

Related Questions