Patrick
Patrick

Reputation: 4905

php variable parameters

i have a function that accepts variable number of parameters (meaning I can put X around of parameters onto that function:

MSETNX key value [key value ...]

Both key and value has to be string. Say i have another array with the following structure:

$a = array( 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3');

What's the most effective way to put $a as the parameters for the MSETNX function?

Thank you!

Upvotes: 0

Views: 272

Answers (3)

Neil
Neil

Reputation: 3041

The question is a little unclear in respect of the requisite for string input;

If you need the whole parameter to be a single string, use:

MSETNX(http_build_query($a));

If you need each element (keys and values) to be converted to strings, try this:

MSETNX(array_combine(
    array_map(array_keys($a),"strval"),
    array_map(array_values($a),"strval")
));

Neither seem particularly useful to me, but perhaps you can use this combined with Amber's suggestion?

Upvotes: 0

Amber
Amber

Reputation: 526613

If the function must take varargs, as opposed to just accepting an array,

foreach($a as $k => $v) {
  $b[] = $k;
  $b[] = $v;
}
call_user_func_array('MSETNX', $b);

Upvotes: 1

MrGlass
MrGlass

Reputation: 9262

The most effective way would be to simply pass the array, EG.: MSETNX($a);

Upvotes: 0

Related Questions