1

OK, I know it sounds weird but I need to make a function that will receive two parameters the first one is a string and the second an array (containing strings).

This function will then call sprintf. My first parameter will be $format and my array will correspond to the various $args.

How can I achieve this (if possible)?

Thanks!

AlexV
  • 22,658
  • 18
  • 85
  • 122

2 Answers2

4

Well you want the vsprintf() function.

Orbling
  • 20,413
  • 3
  • 53
  • 64
  • Yep, that's pretty much it. PHP has a function for almost anything. – Evan Mulawski Dec 01 '10 at 20:24
  • 1
    Although annoyingly it does not appear to have a function that would achieve what the OP wanted for a *built-in* function if indeed the array variant did not exist. For user-defined, you can use `call_user_func_array()`. – Orbling Dec 01 '10 at 20:27
  • @Orbling Nah, vsprintf is exactly what I was looking for :) Thanks Orbling! – AlexV Dec 01 '10 at 20:28
  • 1
    @AlexV Yes, in this case the array variant of `sprintf()` exists, I meant for other *built-in* functions, there is no general `apply()` function. Hopefully PHP has array variants of all variable argument functions. As *Evan* says, there are so many functions, I will not check! ;-) – Orbling Dec 01 '10 at 20:31
  • @Orbling Yeah now I understand what you wanted to point out. Thanks for the input! – AlexV Dec 01 '10 at 20:39
2

Like Orbling answered, for this particular case you need vsprintf.

But, in a generic case, to call a function with variable number of parameters, you can use func_get_args() inside the function which you desire to accept multiple (any number of variable arguments). This function (when called inside your function) returns an array containing all the parameters passed while calling your function.

Sandeepan Nath
  • 9,966
  • 17
  • 86
  • 144
  • +1 Aye, there are a whole set of functions for handling variable argument and anonymous functions/callbacks that people use surprisingly rarely in PHP. See: http://uk.php.net/manual/en/ref.funchand.php – Orbling Dec 01 '10 at 20:33
  • 1
    @Orbling Thanks and yes, there are so many such interesting functions. I was so happy the first day I came to know about this function. Another set of functions which made me so happy was the magic functions set http://php.net/manual/en/language.oop5.magic.php. See this question http://stackoverflow.com/questions/4143722/solved-php-faked-multiple-inheritance-having-object-attributes-set-in-fake-pa to see how `__get()` helped me in a difficult situation. – Sandeepan Nath Dec 01 '10 at 20:37
  • There are indeed many useful functions to get to grips with. My favourites in PHP are the functional-programming like `array_*` functions which take *callbacks*, if you use those in combination with `create_function()` you can really simplify data processing. – Orbling Dec 01 '10 at 20:53