Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass variable number of arguments to sprintf() function?

Tags:

string

php

printf

In my web page, if a user choses certain options in a form, say

1. A -  Chosen
2. B -  Chosen
3. C -  Not Chosen

Then, sprintf() function in my script should accept that number of arguments -

sprintf("%s %s", valueOf(A), valueOf(B));

If all three are chosen, then

sprintf("%s %s %s", valueOf(A), valueOf(B), valueOf(C));

How can I achieve this?

like image 918
Shubham Avatar asked Mar 29 '12 11:03

Shubham


People also ask

How do you pass variable arguments to a function?

Reading Variable Arguments inside a functionCreate a list of variable arguments using va_list i.e. va_list varList; va_list varList; Now initialize the list using va_start() i.e.

Can we pass a variable argument list to a function at runtime?

B. Explanation: Every actual argument list must be known at compile time. In that sense it is not truly a variable argument list.

How many arguments are passed to the printf method?

Printf can take as many arguments as you want. In the man page you can see a ... at the end, which stands for a var args. If you got 96 times %s in your first argument, you'll have 97 arguments (The first string + the 96 replaced strings ;) ) Show activity on this post.


2 Answers

What you want is probably the vsprintf function. It takes an array as the set of arguments. So in your case, you'd have something like this:

$args = <array_of_chosen_options>;
$fmt = trim(str_repeat("%s ", count($args)));
$result = vsprintf($fmt, $args);
like image 180
Aleks G Avatar answered Oct 16 '22 08:10

Aleks G


  1. Generate the string of %s %s... dynamically
  2. Use vsprintf instead of sprintf
# // FOR DEMONSTRATION \\
$_POST["A"] = "subscribe_to_this";
$_POST["B"] = "subscribe_to_that";
# \\ FOR DEMONSTRATION //

$chosen = array();
if (isset($_POST["A"])) $chosen[] = $_POST["A"];
if (isset($_POST["B"])) $chosen[] = $_POST["B"];
if (isset($_POST["C"])) $chosen[] = $_POST["C"];

$format = implode(" ", array_fill(0, count($chosen), "%s"));
echo vsprintf($format, $chosen);
like image 22
Salman A Avatar answered Oct 16 '22 07:10

Salman A