How to pass an array as parameters or arguments?

Asked

Viewed 409 times

3

I have two functions:

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

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

And I also have a variable that receives function parameters in the form of a 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 don’t want to manually pass because the function frutas for example, it has 3 parameters and not 2. And I would like it to be automatic, passing all arguments. As if it were a foreach.

There’s a way I can do this?

1 answer

3


You don’t have much control over it, a lot can go wrong. You have to know what you’re doing.

PHP 5.6

example(...$array);

Documentation. This is usually called splat.

PHP previous 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 also, or do another that accepts a array. It’s much better. Just do it when there’s no other way. Still, for a few arguments (and it’s rare not to be so) I would always do it by hand.

  • Is it good to avoid? In my case n has how I do manually...

  • First because it’s Gambi. Second because it’s not necessary. Third because it’s not easy to do it right, but if it is, it was easy to do it manually. Why not? I find it impossible.

  • What I’m trying to do is the following: Use functions outside the server, in another. Then in case I need to pass the parameters to use the function and it goes in array form so there is no way I can do it manually, since each function is different.

  • This doesn’t make sense.

  • pq? Sorry I’m a bit inexperienced...

  • If it doesn’t make sense, you have to explain. Then who knows can do it. You}put a manual example in the question.

  • I can chat with you?

  • Now I understand what you mean, Really my question has nothing to do with what I said in the comment, is why in the case I asked the question so that it is not only for me, solve my doubt and also help others. If I went to explain everything in the question she would get too big and not go straight to the point. I merely commented on what I was trying to do with the answer to this question

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.