3

I need to pass params (like: 'param1', 'param2', 'param3') to the method... but I have array of params (like: array('param1', 'param2', 'param3')). How to convert array to params?

function foo(array $params) {

    bar(
        // Here should be inserted params not array.
    );

}
daGrevis
  • 21,014
  • 37
  • 100
  • 139

3 Answers3

5

Use the function call_user_func_array.

For example:

call_user_func_array('bar', $params);
ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • I tried like [this](http://pastie.org/2158401), but it gives me [an error](http://pastie.org/2158405). – daGrevis Jul 03 '11 at 13:42
  • I think you passed a string for $data. – ComFreek Jul 03 '11 at 13:52
  • Nope. `list_users(array('username', 'email'), 10, 0);` – daGrevis Jul 03 '11 at 14:05
  • But you call with `call_use_func_array` the function `list_users` with the parameters 'username' and 'email'. But your function requires an array, an integer and again an integer. So the $data array must contain the parameters of the list_users function. – ComFreek Jul 03 '11 at 14:16
  • In case you wanted to call method of a class use it this way `call_user_func_array([$instanceOfClass, "method"], $params);` – Bikal Basnet Feb 25 '19 at 16:39
1

If you know the param names you could to the following

$params = array(
    'param1' => 'value 1',
    'param2' => 'value 2',
    'param3' => 'value 3',
);

function foo(array $someParams) {
    extract($someParams);  // this will create variables based on the keys

    bar($param1,$param2,$param3);
}

Not sure if this is what you had in mind.

Adrian World
  • 3,118
  • 2
  • 16
  • 25
0

You can convert one to the other like this:

function foo(array $params)
{
    bar(...$params);
}

or go straight to bar:

bar(...$array);

For the "bar" function to receive several parameters you can use:

function bar(...$params)
{
    //$params is a array of parameters
}

or

function bar($p1, $p2, $p3)
{
    //$pn is a variables
}

or

function bar($p1, ...$pn)
{
    //$p1 is a variable
    //$pn is a array of parameters
}

but a lot of attention with the types and quantity of parameters to not give you problems.

visite: Function Arguments

RoCkHeLuCk
  • 199
  • 1
  • 5