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?
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.
B. Explanation: Every actual argument list must be known at compile time. In that sense it is not truly a variable argument list.
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.
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);
%s %s...
dynamicallyvsprintf
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With