0

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!

1
  • Is there a reason why you don't like to use a Redis Wrapper class like php5-redis ? Commented Jan 9, 2011 at 8:06

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Whoops yep. Too much Python. >.>
FYI if you want a function to support both varargs AND an array of said args, I find this sort of thing helps - if(func_num_args()!=1||!is_array($arg)) return thisFunc(func_get_args());. You can do fancier call_user_func stuff too if you don't want to use the function/class name.
0

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

2 Comments

parameter has to be string, not array
you mean flattening the array into a string? like MSETNX(http_build_query($a))?
0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.