Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Pass array as variable-length argument list

I have really simple problem in my PHP script. There is a function defined which takes variable length argument list:

function foo() {
  // func_get_args() and similar stuff here
}

When I call it like this, it works just fine:

foo("hello", "world");

However, I have my variables in the array and I need to pass them "separately" as single arguments to the function. For example:

$my_args = array("hello", "world");
foo(do_some_stuff($my_args));

Is there any do_some_stuff function which splits the arguments for me so I can pass them to the function?

like image 217
Pavel S. Avatar asked Jan 28 '12 12:01

Pavel S.


People also ask

Does PHP support variable length arguments?

PHP supports variable length argument function. It means you can pass 0, 1 or n number of arguments in function. To do so, you need to use 3 ellipses (dots) before the argument name. The 3 dot concept is implemented for variable length argument since PHP 5.6.

Can we pass array as argument in PHP?

You can pass an array as an argument. It is copied by value (or COW'd, which essentially means the same to you), so you can array_pop() (and similar) all you like on it and won't affect anything outside. function sendemail($id, $userid){ // ... }

What is a variable length argument list?

Variable-length argument lists, makes it possible to write a method that accepts any number of arguments when it is called. For example, suppose we need to write a method named sum that can accept any number of int values and then return the sum of those values.

Can you pass functions as parameters in PHP?

There is another type of function known as PHP Parameterized functions, these are the functions with pre defined parameters. You'll pass any number of parameters inside a function. These passed parameters act as variables in your function. They are declared inside the brackets, after the function name.


1 Answers

Use

  • ReflectionFunction::invokeArgs(array $args)

or

  • call_user_func_array( callback $callback, array $param_arr)
like image 129
Crozin Avatar answered Oct 12 '22 12:10

Crozin