How to pass an array as parameters or arguments?

3

I have two functions:

function example($param1, $param2)
{
    echo $param1 . $param2;
}

function frutas($fruta1, $fruta2, $fruta3)
{
    echo $fruta1 . $fruta2 . $fruta3;
}

I also have a variable that gets the parameters of the functions in the form of an array :

$array = ['param1', 'param2'] // para função example()
or $array = ['fruta1', 'fruta2', 'fruta3'] // para função fruta()

I can manually pass the values this way:

example($array[0], $array[1])

I do not want to pass manually because the frutas function for example has 3 parameters and not 2. And I would like it to be automatic, passing all arguments. As if it were a foreach .

Is there a way for me to do this?

    
asked by anonymous 28.05.2016 / 01:17

1 answer

3

I do not know if it's what you want, but you do not have much control over it, a lot can go wrong. You have to know what you are doing.

PHP 5.6

example(...$array);

Documentation . This is often called splat .

PHP prior to 5.6

call_user_func_array("example", $array);

Documentation .

I recommend avoiding this as much as possible. If you are going to create the function, then make it accept the array as well, or make another that accepts an array . It is way better. Do it only when you have no other way. Even so, for a few arguments (and it's rare not to be so) I would always do it.

    
28.05.2016 / 01:35