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

}
2
  • When you pass the $params array will you know the param names? Commented Jul 3, 2011 at 14:05
  • @Adrian, yes. Can you suggest something? Commented Jul 3, 2011 at 14:18

3 Answers 3

5

Use the function call_user_func_array.

For example:

call_user_func_array('bar', $params);
Sign up to request clarification or add additional context in comments.

5 Comments

I tried like this, but it gives me an error.
I think you passed a string for $data.
Nope. list_users(array('username', 'email'), 10, 0);
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.
In case you wanted to call method of a class use it this way call_user_func_array([$instanceOfClass, "method"], $params);
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.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.