Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Associative Array to Function in PHP

I'm curious to know if there is some way to call a function using an associative array to declare the parameters.

For instance if I have this function:

function test($hello, $world) {
    echo $hello . $world;
}

Is there some way to call it doing something like this?

call('test', array('hello' => 'First value', 'world' => 'Second value'));

I'm familiar with using call_user_func and call_user_func_array, but I'm looking for something more generic that I can use to call various methods when I don't know what parameters they are looking for ahead of time.

Edit: The reason for this is to make a single interface for an API front end. I'm accepting JSON and converting that into an array. So, I'd like different methods to be called and pass the values from the JSON input into the methods. Since I want to be able to call an assortment of different methods from this interface, I want a way to pass parameters to the functions without knowing what order they need to be in. I'm thinking using reflections will get me the results I'm looking for.

like image 813
cbulock Avatar asked Mar 30 '13 16:03

cbulock


People also ask

Which associative array is used to pass data to PHP?

The $_POST is an associative array of variables. These variables can be passed by using a web form using the post method or it can be an application that sends data by HTTP-Content type in the request.

What is an associative array in PHP?

Associative Array - It refers to an array with strings as an index. Rather than storing element values in a strict linear index order, this stores them in combination with key values. Multiple indices are used to access values in a multidimensional array, which contains one or more arrays.

How to pass argument in PHP?

PHP Function ArgumentsArguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.


2 Answers

With PHP 5.4+, this works

function test($assocArr){
  foreach( $assocArr as $key=>$value ){
    echo $key . ' ' . $value . ' ';
  }
}

test(['hello'=>'world', 'lorem'=>'ipsum']);
like image 193
Gary Avatar answered Sep 23 '22 01:09

Gary


Check the php manual for call_user_func_array

Also, look up token operator (...). It is a way to use varargs with functions in PHP. You can declare something like this: -

function func( ...$params)
{
    echo $params[0] . ',' . parama[1];
}
like image 30
Xnoise Avatar answered Sep 22 '22 01:09

Xnoise