Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass array as multiple parameters to function?

I have a parameters array:

$params[1] = 'param1';
$params[2] = 'param2';
$params[3] = 'param3';
...
$params[N] = 'paramN';

I have a caller to various functions:

$method->$function( $params );

How can I parse the $params array, so multiple (and unlimited) parameters can be passed to any function:

$method->$function( $params[1], $params[2], ..., $params[N] );

The idea is to utilize the url rewrite like this:

http://domain.com/class/method/parameter/parameter/parameter/...

like image 408
Blackbeard Avatar asked Apr 27 '10 10:04

Blackbeard


People also ask

Can we pass array as a parameter of function?

Just like normal variables, simple arrays can also be passed to a function as an argument, but in C/C++ whenever we pass an array as a function argument then it is always treated as a pointer by a function.

How do you pass an array as a function parameter in JavaScript?

Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.

How do you pass multiple variables to a function?

The * symbol is used to pass a variable number of arguments to a function. Typically, this syntax is used to avoid the code failing when we don't know how many arguments will be sent to the function.


2 Answers

You need to use call_user_func_array

call_user_func_array( array($method, $function), $params);
like image 196
Yacoby Avatar answered Oct 03 '22 15:10

Yacoby


As of PHP 5.6 you can use argument unpacking:

function add($a, $b, $c) {
    return $a + $b + $c;
}

$numbers = [1, 2, 3];
echo add(...$numbers);
like image 16
MichalVales Avatar answered Oct 03 '22 17:10

MichalVales